我有两个模型,如:
class Car(models.Model):
name = models.CharField(max_length=255)
class CarImage(models.Model):
car = models.ForeignKey(Car, related_name='photos')
photo = models.ImageField(upload_to='car/')
从上面的模型我想要获取汽车的所有图像。所以我按照以下方式编写了我的serailzer:
class CarSerializer(serializers.ModelSerializer):
"""
"""
_id = serializers.ReadOnlyField(source='pk')
photos = serializers.RelatedField(many=True, read_only=True)
class Meta:
model = Car
fields = ('my_field_here', )
class CarImageSerializer(serializers.ModelSerializer):
"""
"""
_id = serializers.ReadOnlyField(source='pk')
class Meta:
model = CarImage
fields = ('my_field_here', )
但在CarSerializer
序列化工具照片字段中显示此错误RelatedField.to_representation() must be implemented for field . If you do not need to support write operations you probably want to subclass
ReadOnlyField instead.
但我使用PrimaryKeyRelatedField
而不是RelatedField,然后它工作正常,我得到主键列表,但我想要所有字段。
我还尝试将CarImageSerializer
用作
在Carserializer
decalared
assets_keys = serializers.SerializerMethodField()
def get_assets_keys(self, obj):
return AssetKeySerializer(obj.asset_keys.all(), context=self.context).data
但是它不能序列化资产键列表,它需要单个对象。
所以我的问题是可以使用序列化程序获取相关的对象数据。如果是,我需要在序列化器中纠正什么?
我的回答必须如下:
[
{
"_id": 1,
"name": "first",
"photos": [
"name":"xyz",
"photo":"path_to_photo"
]
},
{
"_id": 1,
"name": "second",
"photos": [
"name":"abcddd",
"photo":"path_to_photo"
]
},
]
答案 0 :(得分:1)
您需要在CarSerializer
中使用nested serializer:
photos = CarImageSerializer(many=True, read_only=True)