amit
amit

Reputation: 373

How to reverse serialize in django with many to many relations

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"
                }
            }
        ]
  }

Upvotes: 5

Views: 2188

Answers (1)

Shakil
Shakil

Reputation: 4630

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

Upvotes: 7

Related Questions