danielrvt danielrvt - 1 year ago 77
Python Question

Django - Filter objects older than X days

I need to filter objects older than

number of days. I realize this question exists here: django filter older than day(s)?

However, I not trying to do exactly that, since the number of days, in my case lives inside the model:

class Post(models.Model):
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

This is the query I have so far:

EDIT: I changed the days.plan part for
Meaning that the number of days that I'm using to compare is in each post's

Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=the_post.plan.days))

Note the
part of the query. How can I reference
for this query? Is it possible?

Answer Source

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'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download