5

I have first made category crud, and then product crud with many-to-many relation with category.
models.py (category):

class Category(models.Model):
    name = models.CharField(max_length=191, blank=False, null=False)
    description = models.TextField(blank=True, null=True)

models.py (product):

class Product(models.Model):
    product_code = models.CharField(max_length=191, blank=False, null=False)
    name = models.CharField(max_length=191, blank=False, null=False)
    description = models.TextField(blank=False, null=False)
    price = models.DecimalField(max_digits=19, decimal_places=2)
    photo = models.ImageField(upload_to='pictures/products/', max_length=255, null=False, blank=False)
    category = models.name = models.ManyToManyField(Category)

How to achieve following result:

  {
        "categories": [
            {
                "id": 1,
                "name": "Indoor Muscle Training",
                "description": null,
                "products":{
                       "name":"product_name",
                       "code":"product_code"
                }
            },
            {
                "id": 2,
                "name": "Outdoor Muscle Training",
                "description": null,
                "products":{
                       "name":"product_name",
                       "code":"product_code"
                }
            }
        ]
  }
Nathan
  • 449
  • 1
  • 7
  • 23
amit
  • 353
  • 1
  • 3
  • 19
  • Possible duplicate of [Django rest framework serializing many to many field](https://stackoverflow.com/questions/33182092/django-rest-framework-serializing-many-to-many-field) – Manuel Fedele Mar 19 '19 at 09:31
  • Not exactly that. I can generate categories inside products . But I want products inside categories. – amit Mar 19 '19 at 09:40

1 Answers1

7

using serializer-method field can be an option for this case. Our goal is get product information from category serializer. So for this

class CategorySerializer(serializers.ModelSerializer):
    products = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ('') # add relative fields

   def get_products(self, obj):
       products = obj.product_set.all() # will return product query set associate with this category
       response = ProductSerializer(products, many=True).data
       return response
Shakil
  • 4,520
  • 3
  • 26
  • 36
  • It says, 'Category' object has no attribute 'product_set' – amit Mar 19 '19 at 10:38
  • @amit do you add any related name in your model defination ? I haven't seen from your post . related reading [link](https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships) this should work :( – Shakil Mar 19 '19 at 10:46
  • you can try `obj.product.all()` but previous this also should work, if you don't add any related name in you django model defination. – Shakil Mar 19 '19 at 10:47