How to get only the last month's records present in the database, using queryset django?

Viewed 318

I need to get only the objects of the last month present in the DB. I don't mean the last 30 days or the last calendar month, but the most recent month recorded in the database... I have seen that django has the latest() function that returns the most recent object in the table based on in the given field(s), however I want it to return multiple objects based on the given month.

revisoes = Revisao.objects.filter(apicultor__in=apicultores).order_by('-data_registro')

This is the queryset I am using, only it returns all revisions for a given beekeeper. I need it to return only revisions based on the last month of the data_registro field.

2 Answers

You can determine the previous month with a relativedelta object [readthedocs.io] of the dateutil package [readthedocs.io] and use this to retrieve items from the last month:

from dateutil.relativedelta import relativedelta
from django.utils.timezone import now

revisoes = Revisao.objects.filter(
    apicultor__in=apicultores, data_registro__gte=now()-relativedelta(months=1)
).order_by('-data_registro')

or if you want to retrieve items since the beginning of the month, you use:

from calendar import monthrange
from datetime import datetime

some_datetime = datetime(2022, 1, 28, 15, 15)
start = some_datetime.date().replace(day=1)
end = some_datetime.date().replace(day=monthrange(some_datetime.year, some_datetime.month)[1])

revisoes = Revisao.objects.filter(
    apicultor__in=apicultores, data_registro__range=[start, end]
).order_by('-data_registro')

or if data_registro is a DateTimeField:

from calendar import monthrange
from datetime import datetime

some_datetime = datetime(2022, 1, 28, 15, 15)
start = some_datetime.date().replace(day=1)
end = some_datetime.date().replace(day=monthrange(some_datetime.year, some_datetime.month)[1])

revisoes = Revisao.objects.filter(
    apicultor__in=apicultores, data_registro__date__range=[start, end]
).order_by('-data_registro')

SOLUTION: I solved my problem as follows:

meses = [obj.data_registro for obj in revisoes]
ultimo_mes = max(meses)
ultimo_mes = ultimo_mes.strftime("%Y-%m")
revisoes_recentes = Revisao.objects.filter(apicultor__in=apicultores, data_registro__contains=ultimo_mes)
Related