开发者社区> 问答> 正文

Python Django显示嵌套对象

嗨,我是django rest框架的新手,我正在尝试序列化3个嵌套模型。这些关系是:hotel_social_media_typehotel_social_media具有一对多的关系,并且hotelhotel_social_media具有一对多的关系。现在,我只能将hotel序列化为hotel_social_media,但是不能序列化hotel_social_media_type

这是我的序列化器:

class SocialMediaTypeSerializer(serializers.ModelSerializer):
    """Serializes social media type"""

    class Meta:
        model = models.SocialMediaType
        fields = ('name', 'icon', 'url')


class HotelSocialMediaSerializer(serializers.ModelSerializer):
    """Serializes media files"""
    hotel_social_media_type = SocialMediaTypeSerializer(many=False, read_only=True)

    class Meta:
        model = models.HotelSocialMedia
        fields = ('url', 'hotel_social_media_type')


class HotelSerializer(serializers.ModelSerializer):
    """Serializes Restaurat, Bars, TouristInformation and Tourist Spots """

    hotel_images = HotelImageSerializer(many=True, read_only=True)
    hotel_social_media = HotelSocialMediaSerializer(many=True, read_only=True)

    class Meta:
        model = models.Hotel
        fields = ('id', 'name', 'hotel_images', 'hotel_social_media')

楷模:

class Hotel(models.Model):
    """Database model for hotels"""
    name = models.CharField(max_length=50)

    def __str__(self):
        """Return the model as a string"""
        return self.name

class HotelImage(models.Model):
    """Image upload for hotel"""
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=250)
    path = models.ImageField(upload_to='images/')
    created_on = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)

    hotel = models.ForeignKey(Hotel, related_name='hotel_images', on_delete=models.CASCADE, null=True)

    def __str__(self):
        """Return the model as a string"""
        return self.name

class SocialMediaType(models.Model):
    """Social Media Type eg: fb, twitter"""
    name = models.CharField(max_length=50)
    icon = models.ImageField(upload_to='images/')
    url = models.CharField(max_length=50)

    def __str__(self):
        """Return the model as a string"""
        return self.name

class HotelSocialMedia(models.Model):
    """Social Media"""

    hotel = models.ForeignKey(Hotel, related_name='hotel_social_media', on_delete=models.CASCADE, null=True)
    type = models.ForeignKey(SocialMediaType, related_name='hotel_social_media_type', on_delete=models.CASCADE, null=True)

    name = models.CharField(max_length=50)
    url = models.CharField(max_length=50)

    def __str__(self):
        """Return the model as a string"""
        return self.name

当前结果是:

{
  "id": 1,
  "name": "Alta Vista",
  "hotel_images": [
    {
      "id": 1,
      "name": "Alta Vista",
      "path": "http://127.0.0.1:8000/media/images/hotel-1.jpg"
    }
  ],
  "hotel_social_media": [
    {
      "url": "https://www.facebook.com/abscbnNEWS"
    }
  ]
}

我想要的是:

{
  "id": 1,
  "name": "Alta Vista",
  "hotel_images": [
    {
      "id": 1,
      "name": "Alta Vista",
      "path": "http://127.0.0.1:8000/media/images/hotel-1.jpg"
    }
  ],
  "hotel_social_media": [
    {
      "url": "https://www.facebook.com/abscbnNEWS",
      "hotel_social_media_type": {
        "name": "Facebook",
        "icon": "http://127.0.0.1:8000/media/images/fb-1.jpg"
      }
    }
  ]
}



 \` hotel_social_media \`  must also display  \` hotel_social_media_type \` 

问题来源:stackoverflow

展开
收起
is大龙 2020-03-25 09:21:10 2766 0
1 条回答
写回答
取消 提交回答
  • 根据您的模型,您必须在HotelSocialMediaSerializer中使用type关键字而不是hotel_social_media_type。因为您的HotelSocialMedia具有与HotelSocialMediaType相关的type字段。更改关键字可以解决您的问题。

    class HotelSocialMediaSerializer(serializers.ModelSerializer):
       """Serializes media files"""
        type = SocialMediaTypeSerializer(many=False, read_only=True)
    
        class Meta:
            model = models.HotelSocialMedia
            fields = ('url', 'type')
    

    如果要使用hotel_social_media_type关键字,则可以使用SerializerMethodField这样:

    class HotelSocialMediaSerializer(serializers.ModelSerializer):
       """Serializes media files"""
        hotel_social_media_type = serializers.SerializerMethodField()
    
        class Meta:
            model = models.HotelSocialMedia
            fields = ('url', 'hotel_social_media_type')
    
        def get_hotel_social_media_type(self.obj):
            serializer = SocialMediaTypeSerializer(obj.type)
            return serializer.data
    

    回答来源:stackoverflow

    2020-03-25 09:21:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载