I have a model like this:
class RentDue(models.Model):
balance = DecimalField()
day_due = IntegerField() # e.g. 1-5, representing the 1st through 5th of the month
I want to be able to annotate a queryset using the integer from day_due
to create a new attribute rent_due_date
so that I can filter on the next month's due date like this:
from datetime import date, timedelta
# create RentDue instances -- one due on the 1st another on the 3rd
rent_due_first = RentDue.objects.create(day_due=1)
rent_due_third = RentDue.objects.create(day_due=3)
# query for all RentDue on the 1st or earlier
RentDue.objects.annotate(
rent_due_date=date(2022, 12, F('day_due'))
).filter(
rent_due_date__lte=date(2022, 12, 1)
)
# -> returns [rent_due_first]
# query for all RentDue on the 3rd or earlier
RentDue.objects.annotate(
rent_due_date=date(2022, 12, F('day_due'))
).filter(
rent_due_date__lte=date(2022, 12, 3)
)
# -> returns [rent_due_first, rent_due_third]
However, passing in the F
expression to date
raises TypeError: an integer is required (got type F)
I've tried using ExpressionWrapper
as laid out in this answer as well as TruncDate
but I'm getting some weird errors I don't quite get.
A possible solution would be to annotate the entire queryset with DateField of next_month
(hard-coded to date(2022, 12, 1)
and then being able to use that in an F
expression/ExpressionWrapper
but that seems like a lot of work as well.
Just need some ideas to get my mind working.