I need to filter objects older than
title = models.CharField(max_length=200)
description = models.CharField(max_length=500)
createdAt = models.DateTimeField(default=datetime.now, blank=True)
plan = models.ForeignKey(Plan) # This model has the number of days
Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=the_post.plan.days))
With a small tweak in your Plan model, it is indeed possible to do what you want.
First of all, you'll need to change your Plan
days field, which is probably an
IntegerField, to DurationField.
Now the catch is that we have to use ExpressionWrapper to achieve the exact same result inside Postgres as the result you'd achieve in Python if you were to get the plan in a separate query.
Finally, your query should be something like:
from django.db.models import F, ExpressionWrapper, DateTimeField Post.objects.annotate(target_date=ExpressionWrapper(datetime.now() - F('plan__days'), output_field=DateTimeField())).filter(createdAt__lte=F('target_date'))