序列化器获取RelatedField

时间:2018-09-25 12:01:23

标签: python django python-3.x django-models django-rest-framework

下面是我的serializers.py和model.py类的代码

serializers.py

class SliderImageSerializers(serializers.ModelSerializer):
    class Meta:
        model=SliderImage
        fields='url','rank'

class ItemVariationsSerializer(serializers.ModelSerializer):
    # items = ItemsSerializer(many=True, read_only=True)
    class Meta:
        model = ItemVariation
        fields ='price','item_code','image'

class RestaurantSerializers(serializers.ModelSerializer):
    items = ItemVariationsSerializer(many=True, read_only=True)
    sliders = SliderImageSerializers(many=True, read_only=True)
    class Meta:
        model=Restaurant
        fields=('__all__')

models.py

class ItemVariation(models.Model):
    restaurant=models.ForeignKey(Restaurant,on_delete=models.CASCADE)
    item=models.ForeignKey(Item,on_delete=models.CASCADE)
    price=models.IntegerField(blank=True,null=True,default=0)
    item_code=models.CharField(max_length=500)
    keyword= models.ManyToManyField(Keyword)
    image=models.ImageField(upload_to='dishes/', blank=True, null=True)

    def __str__(self):
        return str(self.id)

下面是我收到的回复

响应:

{
    "id": 1,
    "sliders": [
        {
            "url": "/media/restaurant/download_2.jpeg",
            "rank": 1
        }
    ],
    "name": "Haveli",
    "email": "test@tet.com",
    "web": "wdew",
    "short_description": "dsfsdf",
    "description": "fsdfsd",
    "phone": 21315,
    "lat": 30.704649,
    "lng": 76.717873,
    "address1": "dsff",
    "address2": "vfdg",
    "city": "sdfds",
    "state": "fs",
    "postalcode": "sdfsd",
    "avg_rating": 1,
    "price": 0,
    "restaurant_type": 1,
    "keywords": [
        1,
        2,
        3
    ]
}

我需要在 RestaurantSerializers 响应

中添加 ItemVariationsSerializer

但是我需要以下响应

  

{
      “ id”:1,
      “滑块”:[
          {
              “ url”:“ /media/restaurant/download_2.jpeg”,
              “等级”:1
          }
      ],
      “ name”:“ Haveli”,
      “电子邮件”:“ test@tet.com”,
      “项目”:[
      {
      “ price”:“ 213”
      “ item_code”:“测试人员”
      }
      ]
      “关键字”:[
          1,
          2,
          3
      ]}

我需要您的帮助以得到需要的答复。谢谢

0 个答案:

没有答案