Django Rest Framework Serializer not printing nested relationship

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?

Looking at DRF docs example, what if you add related_name="items" to order_id field?

1 Like

That was the issue indeed. Missed looking at the Models from the example and focused only in the Serializer class. Thanks very much!!

1 Like