Home > Mobile >  Object data becomes empty after serializing
Object data becomes empty after serializing

Time:10-05

    user = User.objects.filter(id=payload['id']).first()

carts = AddToCart.objects.filter(user=user)

sum_price = 0
for i in carts:
    sum_price  = int(i.product.price)

context = {
    'carts': carts,
    'sum_price': sum_price,
}
print(context)

serializer = AddToCartSerializer(context, many=True)
return Response(serializer.data)

**printed 'context' in a terminal looks like this {'carts': <QuerySet [<AddToCart: AddToCart object (3)>]>, 'sum_price': 100}. But after serializing it becomes empty. Can someone help me? **

This is an output in a postman

[
{},
{}
]

AddToCart models.py

class AddToCart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)

AddToCartSerializer serializers.py

class AddToCartSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='User')
product = serializers.ReadOnlyField(source='Product')

class Meta:
    model = AddToCart
    fields = ['user', 'product']

CodePudding user response:

Try following code.

views.py:

# context = {
#    'carts': carts,
#    'sum_price': sum_price,
# }
print('result1', carts)
serializer = AddToCartSerializer(carts, many=True)
data = {
    'carts': serializer.data,
    'sum_price': sum_price,
}
print('result2', data)
return Response(data)

serializers.py:

class AddToCartSerializer(serializers.ModelSerializer):
    class Meta:
        model = AddToCart
        fields = ['user', 'product']
        read_only_fields = ['user', 'product']
  • Related