chai
chai

Reputation: 510

How do I filter model objects by most recently created in Django?

I am working on a website in Django and I have a model 'Question'. The Question model has a field 'date_created' which is a DateTimeField.

from django.db import models
from django.utils import timezone

class Question(models.Model:
    ...
    date_created = models.DateTimeField(default=timezone.now)

In my view, I want to be able to get all the questions that have been asked in the last 10 days. Something like this:

Question.objects.filter(???)

>> <All the questions that have been asked in the last 10 days>

What do I replace '???' with? Thanks in advance.

Upvotes: 2

Views: 576

Answers (2)

chrislondon
chrislondon

Reputation: 12031

You'll want to do this

from django.utils import timezone
from datetime import timedelta

ten_days_ago = timezone.now() - timedelta(days=10)
questions_last_10_days = Question.objects.filter(date_created__gte=ten_days_ago)

You use timedelta to get the datetime of 10 days ago.

Then you use the filter date_created__gte. This is a Django construct that means "date_created that is greater-than or equal to"

Upvotes: 3

getup8
getup8

Reputation: 8228

You might just want to get the most recent N Questions instead.

Question.objects.order_by('-date_created')[:10]

Upvotes: 4

Related Questions