Search code examples
jsondjango-modelsdjango-rest-frameworkmany-to-manydjango-serializer

Why Django Rest API serializers diden't serialize many to many fields correctly


the problem is in OrderProdSerializer class , whene i try to get some informations from OrderProd models i can get the id correctly but it ignore the other fields like "quantity" and "date" .

MODELS :

class Product(models.Model):
    ...
    name  = models.CharField(max_length=100, blank=True, null=True)
    price = models.DecimalField(max_digits=6,decimal_places=2)
    ...
  
class Order(models.Model):
    user    = models.ForeignKey("main.User", on_delete=models.CASCADE)
    details = models.ManyToManyField(Product, through="OrderProd")
    ...
    
    
class OrderProd(models.Model):
    product  = models.ForeignKey(Product, on_delete=models.CASCADE)
    order    = models.ForeignKey(Order  ,  on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0)
    date     = models.DateTimeField(default=timezone.now)
   

the OrderProd serializer :

class OrderProdSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField( source='name')
    product_price= serializers.DecimalField(max_digits=20,decimal_places=2,source='price')
    class Meta:
        model=OrderProd
        fields=["id","product_name","quantity","product_price","date"]
        read_only_fields = ('id',)
  

      
class OrderSerializer(serializers.ModelSerializer):
    details = OrderProdSerializer(many=True)
    class Meta:
        model=Order
        fields=["id","details","created_date","order_date"]
        read_only_fields = ('id', )
            

The result :

[
    {
        "id": 1,
        "details": [
            {
                "id": 1,
                "product_name": "t-shirt",
                "product_price": "20.00",
            }
        ],
        "created_date": "2023-07-25T17:34:45Z",
        "order_date": null
    }
]

what is supposed to be :

[
    {
        "id": 1,
        "details": [
            {
                "id": 1,
                "product_name": "t-shirt",
                "product_price": "20.00",
                "quantity": 2 ,
                "date": "2023-07-25"
            }
        ],
        "created_date": "2023-07-25T17:34:45Z",
        "order_date": null
    }
]

Solution

  • Thank you so much! I have found the solution :

    the solusion is to add source to details

        details = OrderProdSerializer(many=True,read_only=True, source='orderprod_set')
    

    i have made some changes in OrderProdSerializer

    class OrderProdSerializer(serializers.ModelSerializer):
      
        product_name = serializers.CharField( source='product.name')
        product_price = serializers.CharField( source='product.price')
    
        class Meta:
            model=OrderProd
            fields=["id","order","quantity","date","product","product_name","product_price"]
            read_only_fields = ('id', )