0

我有以下型号:

class RestaurantItemImages(models.Model):
    restauraunt_item = models.ForeignKey('RestaurantItem',on_delete=models.CASCADE)
    image = models.ImageField()
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __str__(self):

        return self.restauraunt_item.name


class RestaurantItem(models.Model):
    name            =           models.CharField(max_length=255)
    description     =           models.TextField()
    price           =           models.FloatField()
    restauraunt     =           models.ForeignKey('Restauraunt',on_delete=models.CASCADE)
    featured        =           models.BooleanField(default=False)
    popular         =           models.BooleanField(default=False)
    menu            =           models.ManyToManyField('MenuType')  

    def __str__(self):
        return self.name

我正在使用以下查询在我的 API 视图中获取详细信息,返回结果如下:

featured_items = RestaurantItem.objects.filter(restauraunt__slug=slug).values('name','price','restaurantitemimages__image')


 "featured_items": [
        {
            "name": "Lo Mein Lunch Special",
            "price": 700.0,
            "restaurantitemimages__image": "hero_WlE875w.jpg"
        },
        {
            "name": "Lo Mein Lunch Special",
            "price": 700.0,
            "restaurantitemimages__image": "ASQ.png"
        },
        {
            "name": "Boneless Spare Ribs Lunch Special",
            "price": 100.0,
            "restaurantitemimages__image": null
        },
        {
            "name": "Vegetable Roll (1)",
            "price": 213.0,
            "restaurantitemimages__image": null
        }
    ]

如果您看到同一项目针对不同的图像重复多次,那么有没有一种方法可以将所有图像包含在一个对象中。我也看过 prefetch_related 但在这种情况下对我来说没有意义。

4

2 回答 2

0

看看 Django Rest 框架。嵌套的 ModelSerializer 完全符合您的要求 https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

于 2020-01-06T22:45:25.167 回答
0

我通过定义如下的 RestaurantItemSerializer 解决了这个问题,其中还包括反向外键关系模型:

class RestaurantItemImagesSerializer(ModelSerializer):
    class Meta:
        model = RestaurantItemImages
        fields = ['image']




class RestaurantItemSerializer(ModelSerializer):
    restaurantitemimages_set = RestaurantItemImagesSerializer(many=True)
    class Meta:
        model = RestaurantItem
        fields = ['name','description','price','restaurantitemimages_set']

现在,我不再使用上述过滤器查询,而是简单地调用我的相关对象,然后在基于函数的 API 视图中使用此序列化程序对其进行序列化。

restaurantitem_obj = RestaurantItem.objects.filter(restauraunt__slug=slug)
featured_items = RestaurantItemSerializer(restaurantitem_obj,many=True)

它以我想要的方式给出结果,如下所示:

{
    "featured_items": [
        {
            "name": "Item 1",
            "description": "Test Description",
            "price": 700.0,
            "restaurantitemimages_set": [
                {
                    "image": "/media/WlE875w.jpg"
                },
                {
                    "image": "/media/ASqUIVb.png"
                }
            ]
        },
        {
            "name": "Item2",
            "description": "adasdasd",
            "price": 100.0,
            "restaurantitemimages_set": []
        },
        {
            "name": "Roll (1)",
            "description": "asdasda",
            "price": 213.0,
            "restaurantitemimages_set": []
        }
    ]

}
于 2020-01-06T23:13:06.787 回答