I have a model like this with relationship Booking -- Payment (one to may)
(one Booking can have many Payments)
My problem is that I calling too many expensive queries because of SerializerFieldModel().
class Booking(AbstractItem):
accommodation = models.CharField(max_length=100)
room = models.CharField(max_length=100)
booking_method = models.CharField(max_length=100)
class Payment(AbstractItem):
booking = models.ForeignKey(Booking, on_delete=models.CASCADE)
# paid, refund
status = models.PositiveIntegerField(choices=core_choices.PAYMENT_STATUS, default=core_choices.PAID, null=True)
# cash, credit_card, transfer
payment_method = models.PositiveIntegerField(choices=core_choices.PAYMENT_METHOD, default=core_choices.CASH)
price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
This is my serializer
class BookingXLSXSerializer(ModelSerializer):
paid_cash = SerializerMethodField()
paid_card = SerializerMethodField()
refund_cash = SerializerMethodField()
refund_card = SerializerMethodField()
class Meta:
model = Booking
fields = ('id', 'accommodation ', 'room', 'booking_method', 'paid_cash', 'paid_card', 'refund_cash', 'refund_card')
def get_paid_cash(self, obj):
payments = Payment.objects.filter(booking=obj.id, status=core_choices.CASH)
cash = 0
for payment in payments:
cash += payment.price
return cash
#I noticed that many of the def could use the .all() query then just filter it out
...
this is my view:
class MyExampleViewSet(ListAPIView):
queryset = Booking.objects.all()
serializer_class = BookingXLSXSerializer
pagination_class = SuperLargePagination
I noticed that many SerializerMethodField() could share query and use different filter. Is there a smarter way to reduce calling queries for SerializerMethodField(). Or maybe a way to share the query?