1

I have a model for hotel reservations:

class PaymentRequest(SoftDeleteModel):
     class Meta:
        verbose_name_plural = "PaymentRequests"

    user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False, default=None)
    customer_first_name = models.TextField(blank=False, null=False)
    customer_last_name = models.TextField(blank=False, null=False)
    arrival_date = models.DateTimeField(blank=True, null=True)

What I'd like to do is make a queryset to group my reservations by month and get a count of it. i.e {'jan' : 10, 'feb' : 11, etc..} I've seen some answers like this but does not work quite right, maybe since it was answered 10 years ago.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
haduki
  • 1,145
  • 5
  • 23

1 Answers1

2

I tried something on my already existing model and got a result but instead of 'jan', 'feb' I was able to get the month digit, see if this works for you or not

from django.db.models.functions import Extract

PaymentRequest.objects.annotate(month=Extract('arrival_date','month')).
                       values('month').annotate(dcount=Count('*')).
                       values('month','dcount')

Result would be something like this

<QuerySet [{'month': 2, 'dcount': 2}, {'month': 12, 'dcount': 1}]>
sagar_v_p
  • 66
  • 3