0

I've got established a relationship between 2 models: Order and OrderLine. I've created serializers for both of them following the DRF documentation, yet when printing the serializer.data the nested objects don't show.

Here are my models:

class Order(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session_id = models.CharField(max_length=256)  

class OrderLine(models.Model):
    order_id = models.ForeignKey(Order, on_delete=models.DO_NOTHING)
    product_id = models.ForeignKey(Product, on_delete=models.DO_NOTHING)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    quantity = models.IntegerField()
    total = models.DecimalField(decimal_places=2, max_digits=20)


    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)

These are the serializers:

from rest_framework import serializers

from .models import Order, OrderLine


class OrderLineSerializer(serializers.ModelSerializer):
    """
    OrderLine serializer
    """
    class Meta:
        model = OrderLine
        fields = ['product_id', 'price', 'quantity', 'total']
    


class OrderSerializer(serializers.ModelSerializer):
    """
    Order serializer
    """
    items = OrderLineSerializer(many=True, read_only=True)

    class Meta:
        model = Order
        fields = ['session_id', 'subtotal', 'total', 'items']
        read_only_fields = ['id']

and this is the view:

class OrderAPIViewSet(viewsets.ViewSet):

    def create(self, request):

        order = Order.objects.create(session_id=request.data['session_id'])

        for item in request.data['items']:
            product = Product.objects.get(pk=item['product_id'])
            total = Decimal(item['price'] * item['quantity']) 
            OrderLine.objects.create(
                order_id=order,
                product_id=product,
                price=Decimal(item['price']),
                quantity=item['quantity'],
                total=total
            )

        serializer = OrderSerializer(instance=order)
        print("HERE")
        print(serializer.data)

        return Response(status=status.HTTP_200_OK)

From my REST client I'm posting the following object:

{
            "session_id":uuid,
            "items": [
                {
                    "product_id": product.id,
                    "price": 5.80,
                    "quantity": 2,
                }
            ]
            
        }

but when the print statement in the view is executed this is what's being printed:

{
   "session_id":"4def7bdb-dedb-46aa-9c70-1d9e4f522149",
   "subtotal":"0.00",
   "total":"0.00"
}

notice the the items subresource is not being included.

What am i missing?

6
  • You need to implement create() at your serializer, see the docs of DRF for more info Feb 27, 2021 at 19:22
  • but create is needed only when I want to save the data from a POST request, right? I'm this case I'm just performing a serialization within the View, why would I need create for? Feb 27, 2021 at 19:43
  • then update your question, it's not clear Feb 27, 2021 at 19:51
  • please let me know what is no clear for you and I'll update it accordingly. The question clearly states that the serializer does not print the nested data, doesn't mention anything about saving or creating Feb 28, 2021 at 2:02
  • that part for posting data made that confusion, dropping it will eliminate any confusion Feb 28, 2021 at 9:53

1 Answer 1

0

Because you passed read_only=True parameter to OrderLineSerializer. When your serializer's builtin method to_internal_value() run, clear data not including in your fields list. For more details: read_only

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.