I have the following models:
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
I am using the following query to fetch details in my API view which returns the result as follows:
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
}
]
If you see the same item is being repeated multiple times for different images so is there a way i can have all the images within a single object. I have looked at prefetch_related too but it did not make sense to me in this case.