0

I'm getting a Json response to save it in my database, I need to get the items in line_items object. My Serializer and View works fine if I remove the line_items attribute in the model, but when I try to get that object and save it in the database nothing happens. Maybe I'm missing something in my serializer?

Json Structure:

{
    "id": 123456,
    "email": "[email protected]",
    "created_at": "2017-03-29T15:56:48-04:00",
    "line_items": [
        {
            "id": 56789,
            "title": "Aviator sunglasses",
            "quantity": 1
         },

    {
        "id": 98765,
        "title": "Mid-century lounger",
        "quantity": 1
    }

    ]
}

My model:

class Line(models.Model):
    title = models.CharField(max_length=100)
    quantity = models.IntegerField()


class Order(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField()
    total_price = models.DecimalField(max_digits=6,decimal_places=2)
    line_items = models.ForeignKey(Line)

My Serializer:

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

My View:

@api_view(['POST'])
def orders(request):
    if request.method == 'POST':
        json_str = json.dumps(request.data)
        resp = json.loads(json_str)
        serializer = OrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

3 Answers 3

2

You have a list in the field-key line_items in your response, as per your models you can't accommodate the data in the tables, what you need is ManyToMany relation between Order and Line,

class Order(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField()
    total_price = models.DecimalField(max_digits=6,decimal_places=2)
    line_items = models.ManyToManyField(Line)

and in your serializer,

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = [f.name for f in model._meta.fields] + ['line_items']

    def create(self, validated_data):
        line_items = validated_data.pop('line_items')
        instance = super(OrderSerializer, self).create(validated_data)
        for item in line_items:
            instance.line_items.add(item['id'])
        instance.save()
        return instance
Sign up to request clarification or add additional context in comments.

Comments

1

Just add depth=1 in your serializer. It will do-

class OrderSerializer(ModelSerializer):

    class Meta:
        depth = 1
        fields = '__all__'

Comments

0

I think you should add an explicit line_items field to OrderSerializer. Like this:

class OrderSerializer(ModelSerializer):
    line_items = LineSerializer(many=True)
    class Meta:
        model = Order
        fields = '__all__'

2 Comments

thanks for your reply. Did not works, I think that would be something with the method create.
line_items is a list in the post, but a foreign key in the model. I think it should be a ManyToManyField

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.