我有以下型号:
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 但在这种情况下对我来说没有意义。