Django Rest Framework Serializer not printing nested relationship

77 views
Skip to first unread message

Sebas Bond

unread,
Feb 27, 2021, 2:03:49 PM2/27/21
to Django REST framework
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?

Reply all
Reply to author
Forward
0 new messages