2

I have parent object order and nested object orderDetail.

class Order(Model):
     order_name = CharField(max_length=10)

class OrderDetails(Model):
     order_detail_name = CharField(max_length=10)
     order = ForeignKey('Order')

I want to get/insert/update/delete OrderDetails with order object itself. If I post this json, it should insert/update both objects.

{
    "id": 10,
    "order_name": "Some title",
    "orderDetails": [{
         "id": 15,
         "order_detail_name": "Best Detail"
     }]
}

Thats all. not able to find out any solution. I'm beginner to django/python.

TIA

1
  • anyone can plz help? Commented Jun 8, 2016 at 22:26

1 Answer 1

6

I solved get problem by my self using simpler two liner.

class OrderSerializer(serializers.ModelSerializer):
   orderdetail_set = OrderDetailSerializer(many=true)

POST

def create(self, validated_data):
    order_details_data = validated_data.pop('orderdetail_set')
    order = Order.objects.create(**validated_data)

    for order_detail_data in order_details_data:
        order_detail_data['order'] = order
        OrderDetail.objects.create(**order_detail_data)
    return order    

Now its giving response as expected. :)

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

1 Comment

I can't POST several children in one request, I get the "Invalid data. Expected a dictionary, but got list." error message. As if although I have a many to one relationship like you between the parent and the child models, I can't pass a list in the parent object for the children. Have you done anything special to handle that, or have you encountered that error berfore?

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.