[Answered ]-Simplifying QuerySet calls depending on arguments

2👍

Maybe this helps:

from django.db.models import Q

now = datetime.now()
time_periods = {
    'weekly': Q(year=now.year, month=now.month, day=now.week),  # note from OP: now.week is technically invalid; you actually want to use now.isocalendar()[1]
    'monthly': Q(year=now.year, month=now.month),
    'yearly': Q(year=now.year),
}

instance = TimeModel.objects.get(time_periods[time_period], time_period=time_period)
👤Gerard

Leave a comment