models.py
class Cart(models.Model):
uuid = models.UUIDField(default=uuid.uuid4)
product = models.ForeignKey(Product,
on_delete=models.CASCADE,
null=False,
blank=False)
user = models.ForeignKey(User,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name='cart')
quantity = models.IntegerField(null=False, blank=False, default=1)
amount = models.IntegerField(null=True, blank=True)
def save(self, *args, **kwargs):
self.amount = (self.product.total_price * self.quantity)
return super().save(*args, **kwargs)
serializer.py
class CartSerializer(ModelSerializer):
product = CartProductSerializer(read_only=True)
cart_amount = IntegerField()
class Meta:
model = Cart
fields = ('product', 'quantity', 'amount', 'cart_amount')
views.py
class CartView(ListAPIView):
serializer_class = CartSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
user = self.request.user
return Cart.objects.filter(user=user).annotate(
cart_amount=Sum('amount')
)
response
[
{
"product": {
"title": "bmw",
"total_price": 1099
},
"quantity": 2,
"amount": 2198,
"cart_amount": 2198
},
{
"product": {
"title": "new prod",
"total_price": 11000
},
"quantity": 22,
"amount": 242000,
"cart_amount": 242000
}
]
desire response
[
{
"product": {
"title": "bmw",
"total_price": 1099
},
"quantity": 2,
"amount": 2198
},
{
"product": {
"title": "new prod",
"total_price": 11000
},
"quantity": 22,
"amount": 242000
},
"cart_amount": 244198
]