indexOutOfBounds
indexOutOfBounds

Reputation: 571

Getting reverse relationship model values django

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.

Upvotes: 0

Views: 1055

Answers (2)

indexOutOfBounds
indexOutOfBounds

Reputation: 571

I solved it by defining a RestaurantItemSerializer as follow which also includes the reverse foreign key relationship model:

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']

Now instead of using the above filter query I simply call my related object and then serialize it using this serializer in my function based API View.

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

It gives the result in the way I wanted which is as below:

{
    "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": []
        }
    ]

}

Upvotes: 0

Allamanda Weitgereist
Allamanda Weitgereist

Reputation: 125

take a look at the Django Rest Framwork. A Nested ModelSerializer does exactly what you want https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

Upvotes: 1

Related Questions