Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django get distinct queryset by month from a DateField

class MyModel(models.Model):
    TRANSACTION_TYPE_CHOICES = (
        ('p', 'P'),
        ('c', 'C'),
    )
    status = models.CharField(max_length=50, choices=TRANSACTION_TYPE_CHOICES, default='c')
    user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE,related_name='user_wallet')
    date = models.DateField(auto_now=True)
    amount = models.FloatField(null=True, blank=True)


    def __unicode__(self):
        return str(self.id)

I am a fresher in Python django and have a little knowledge in Django Rest Framework.

I have a model like above and I want to filter the date field by month and get distinct queryset by month.....Is there any default way to do this...

Thanks in advance

like image 372
SEJ Avatar asked May 08 '26 01:05

SEJ


1 Answers

you can use TruncMonth with annotations

from django.db.models.functions import TruncMonth

MyModel.objects.annotate(
    month=TruncMonth('date')
).filter(month=YOURVALUE).values('month').distinct()

or if you need only filter date by month with distinct you can use __month option

MyModel.objects.filter(date__month=YOURVALUE).distinct()

Older django you can use extra, example for postgres

MyModel.objects.extra(
    select={'month': "EXTRACT(month FROM date)"},
    where=["EXTRACT(month FROM date)=%s"],
    params=[5]
    # CHANGE 5 on you value
    ).values('month').distinct()

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!