Django REST framework nested query.

29 views
Skip to first unread message

Shamim Hossain

unread,
Nov 6, 2017, 10:37:10 PM11/6/17
to Django users
 I am switched to Djangorest framework from Nodejs. I don't know how can I start to solve following problem.

I have two django model named Category and Product. In Category model has "is_featured" boolean field.
I need category list in JSON format where is_featured=true and the list of products. The models are like following.


from django.db import models

    class Category(models.Model):
        name=models.CharField(max_length=25, blank=False, null=False)
        is_featured=models.BooleanField(default=False)
        parent=models.ForeignKey('self', on_delete=models.CASCADE)

        def __str__(self):
            return self.name

    class Product(models.Model):
        name=models.CharField(max_length=25, blank=False, null=False)
        category=models.ForeignKey(Category, on_delete=models.CASCADE)
        uom=models.CharField(max_length=10)
        price=models.FloatField()

        def __str__(self):
            return '%s %s %s %s' % (self.name, self.category.name, self.price, self.uom)
My expected category list (is_featured=true) result will be look like following.

{  
  "id":1,
  "name":"Foods",
  "products":[  
     {  
        "id":2,
        "name":"Chicken Fri",
        "price":80
     },
     {  
        "id":4,
        "name":"Tomato Salad",
        "price":20
     }
  ]
},
{  
  "id":3,
  "name":"Vegitable",
  "products":[  
     {  
        "id":3,
        "name":"Potato",
        "price":20
     },
     {  
        "id":6,
        "name":"Bean",
        "price":55
     }
  ]
}

Xavier Ordoquy

unread,
Nov 7, 2017, 1:13:26 AM11/7/17
to 'Kristofer Pettijohn' via Django users
Hi,

You are looking for nested serializers. Documentation explains how to deal with them at: http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

Regards,
Xavier,
Linovia.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/207046d9-00fd-4919-a0b0-8a13e4922e6e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages