2

I am trying to figure out how to set up my nested serializers.

# models.py

class Product(models.Model):
    sku = models.CharField()
    product_name = models.CharField()

class Order(models.Model):
    name = models.CharField()
    address = models.CharField()

class OrderProduct(models.Model):
    order = models.ForeignKey( Order )
    product = models.ForeignKey( Product )
    quantity = models.IntegerField()

So I want to have an api that can create an order in the form of the following:

{
  "name" : "James",
  "address" : "100 Main St",
  "products" : [
              { "sku" : "1234", "quantity" : 1 }
            ]
}

I understand that I would need nest OrderProductSerializer inside OrderSerializer, but how do I implement it here when the "products" data use the field "sku" which is not found in the OrderProduct model. Do I do double-nesting? How does that look like?

# serializers.py

class OrderProductSerializer( serializers.ModelSerializer):
    class Meta:
        model = OrderProduct
        exclude = ()

class OrderSerializer(serializers.ModelSerializer):
    products = OrderProductsSerializer(many=True)
    class Meta:
        model = Order
        exclude = ()

1 Answer 1

2

You are trying to implement Nested Serialize on reverse relationship. So, you have to explicitly provide the relationship name as the parameter to the serializer via source argument.


Try this

class OrderProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderProduct
        fields = '__all__'


class OrderSerializer(serializers.ModelSerializer):
    product = OrderProductSerializer(many=True, source='product_set')

    class Meta:
        model = Order
        fields = '__all__'



For more info reffere these docs
1. DRF Nested Relationship
2. DRF-Reverse Realation
3. What is reverse-relationship in Django

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.