我正在尝试通过反向访问相关模型ImageField
的网址 - ForeignKey
。我已根据文档中的示例尝试了各种可能的选项,但没有运气。任何帮助,将不胜感激。
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(... ...)
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'
答案 0 :(得分:0)
新的DRF 2.3似乎对反向关系有所帮助,并解决了我的问题。
例如,在REST框架2.2中,反向关系需要显式包含在序列化程序类中。
类BlogSerializer(serializers.ModelSerializer): comments = serializers.PrimaryKeyRelatedField(many = True)
class Meta:
model = Blog
fields = ('id', 'title', 'created', 'comments')
从2.3开始,您可以只包含字段名称,相应的序列化字段将自动用于关系。
class BlogSerializer(serializers.ModelSerializer):
"""Don't need to specify the 'comments' field explicitly anymore."""
class Meta:
model = Blog
fields = ('id', 'title', 'created', 'comments')