简体   繁体   English

Django Rest 框架 - 如何序列化嵌套字段

[英]Django Rest Framework - How to serialize nested fields

I have a CustomerSerializer which uses a reverse foreign key field images to return all associated Image objects.我有一个CustomerSerializer ,它使用反向外键字段images来返回所有关联的Image对象。

class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = ('id', 'name', 'images')
        read_only_fields = ('id',)

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ('id', 'name', 'customer')
        read_only_fields = ('id',)

This is what I get from the response:这是我从响应中得到的:

[
   {
       'id': 1,
       'name': 'John Doe',
       'images': [
               1,
               2,
               3,
               4,
               ...
       ]
   }
   ...
]

Question: Instead of just showing images as a list of id s, how can I show a different property ie name ?问题:除了将images显示为id列表之外,我如何显示不同的属性,即name

The desired result would be:期望的结果是:

[
   {
       'id': 1,
       'name': 'John Doe',
       'images': [
               'foo.jpg',
               'bar.jpg',
               'foobar.jpg',
               'lorem.jpg',
               ...
       ]
   }
   ...
]

My first attempt - I replaced the reverse foreign key images with image_names from the SerializerMethodField() in order to select the field name , but I get a null value.我的第一次尝试 - 我用SerializerMethodField()中的image_names替换了反向外键images ,以便 select 字段name ,但我得到了null值。

class CustomerSerializer(serializers.ModelSerializer):
    image_names = serializers.SerializerMethodField()

    def get_image_names(self, obj):
        return obj.images.name

    class Meta:
        model = Customer
        fields = ('id', 'name', 'image_names')
        read_only_fields = ('id',)

Additional Info附加信息

Example models:示例模型:

class Customer(models.Model):
      name = models.CharField()

class Image(models.Model):
      name = models.CharField()
      customer = models.ForeignKey(
        Customer, related_name='images', on_delete=models.CASCADE)

Please let me know if anything is unclear and I will update the question.如果有任何不清楚的地方,请告诉我,我会更新问题。 Thank you.谢谢你。

You need to make another serializer like below您需要制作另一个序列化程序,如下所示

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ('name',)

then update your Customerserializer as below然后如下更新您的 Customerserializer

class CustomerSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True, read_only=True)
    class Meta:
        model = Customer
        fields = ('id', 'name', 'images')

Method 2:方法二:

class CustomerSerializer(serializers.ModelSerializer):
    images = serializers.SerializerMethodField()
    class Meta:
        model = Customer
        fields = ('id', 'name', 'images')
    def get_images(self, obj):
        image_names = obj.images.all().values_list('name', flat=True)
        return image_names

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM