darkhorse
darkhorse

Reputation: 8722

How to filter a queryset using a function in Django?

I have my models set up like this:

class Article(models.Model):
    published_date = models.DateTimeField(defualt = timezone.now())
    .....
    def was_published_in_last_week(self):
        now = timezone.now()
        return now - datetime.timedelta(days = 7) <= self.published_date <= now

The function checks if an article was published within the last 7 days and it works fine.

However, how do I use this to get a query-set of Articles containing the ones which were published in the last 7 days only?

Thanks in advance!

Upvotes: 3

Views: 5308

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You need a custom model manager which works across the model. Functions that you define inside model classes only work on model instances.

You are already using the default model manager objects when you use model classes; you'll just write another one with your custom filter.

# First, define a manager subclass
class PublishedLastWeekManager(models.Manager):
    def get_queryset(self):
        now = timezone.now()
        start = now - datetime.timedelta(days=7)
        return super(PublishedLastWeekManager, self).get_queryset().filter(published_date__range=[start, now])

class Article(models.Model):

    objects = models.Manager() # The default manager.
    published_last_week = PublishedLastWeekManager() # New manager

Now, you can do things like:

Article.published_last_week.all()

Upvotes: 7

Related Questions