我正在尝试ImageField
通过反向访问模型上的 url- ForeignKey
。我根据文档中的示例尝试了各种可能的选项,但没有运气。任何帮助,将不胜感激。
模型.py
class Car(models.Model):
name = models.CharField(... )
@property
def default_image(self):
... ...
return image # <=== returns from the CarImage model
class CarImage(models.Model):
car = models.ForeignKey(Car) # <=== no related_name set, but technically we could use carimage_set
image = models.ImageField(... ...)
serializers.py(尝试)
class CarSerializer(serializers.ModelSerializer):
... ...
image = fields.SerializerMethodField('get_image')
class Meta:
mode = Car
def get_image(self, obj):
return '%s' % obj.default_image.url
例外
'SortedDictWithMetadata' object has no attribute 'default_image'