Доброго времени суток, как передать данные в serializer response_data чтобы возвращась только пагинация (подключена в настройках) и она работает если просто передавать quryset в serializer.
class PaymentsCollectView(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = PaymentsSerializer
queryset = Payments.objects.all()
search_fields = ['id', ]
def get_queryset(self):
# Get request parameters
interval_start = self.request.query_params.get('date_from')
interval_stop = self.request.query_params.get('date_to', datetime.datetime.today().strftime('%Y-%m-%d'))
vending_machine_id = self.request.query_params.get('vending_machine_id')
# Retrieve all payments and order by reverse id
queryset = Payments.objects.all().order_by('-id')
# Filter payments by vending machine ID if provided
if vending_machine_id:
queryset = queryset.filter(vending_machine=vending_machine_id)
# Filter payments by date range
if interval_start:
if interval_stop == interval_start:
# If a single date is provided, filter by that date
queryset = queryset.filter(pay_dt__date=interval_stop)
else:
# If a date range is provided, filter by that range
queryset = queryset.filter(pay_dt__date__range=[interval_start, interval_stop])
# Calculate totals: number of payments, total amount, and total water sold
totals = queryset.aggregate(
total_payments=Count('id'),
total_amount=Sum('pay_amount_cop'),
total_water_sold=Sum('water_volume_sold')
)
# Calculate daily sums
daily_sums = queryset.values('pay_dt__date').annotate(sum_amount=Sum('pay_amount_cop')).annotate(
sum_water=Sum('water_volume_sold')).annotate(count_payments=Count('id')).order_by('-pay_dt__date')
# Prepare response with calculated totals and daily sums
response_data = {
'total_payments': totals['total_payments'],
'total_amount': totals['total_amount'],
'total_water_sold': totals['total_water_sold'],
'daily_sums': list(daily_sums),
}
# Return response
return queryset
serializer
class PaymentsSerializer(serializers.ModelSerializer):
class Meta:
model = Payments
fields = '__all__
чтобы данные летели в таком формате
"count": 3,
"next": null,
"previous": null,
"results": [
{
"total_payments": 8,
"total_amount": 7280,
"total_water_sold": 56.0,
"daily_sums": [
{
"pay_dt__date": "2023-07-19",
"sum_amount": 3640,
"sum_water": 28.0,
"count_payments": 4
},
{
"pay_dt__date": "2023-07-18",
"sum_amount": 1820,
"sum_water": 14.0,
"count_payments": 2
},
{
"pay_dt__date": "2023-07-17",
"sum_amount": 1820,
"sum_water": 14.0,
"count_payments": 2
}
]
}
]