简体   繁体   中英

How to filter an object based on a datetime range in python (Django)

I am trying to create a page with all the most recent posts.

class Post(models.Model):
     title = models.CharField(max_length=40)
     postTime = models.DateTimeField(auto_now_add=True)

I found this example:

 start_date = datetime.date(2005, 1, 1)
 end_date = datetime.date(2005, 3, 31)
 Post.objects.filter(postTime__range=(start_date, end_date))

I know I'm suppose to use the __range function. But how can I make it so that I can get all the posts from a range of today all the way to two weeks ago

something like this:

start_date = datetime.date(date from two weeks ago)
end_date = datetime.date(currentdate)
Post.objects.filter(postTime__range(start_date, end_date))
start_date = end_date - datetime.timedelta(days=14)
from datetime import date, timedelta

Post.objects.filter(postTime__range=(date.today(), date.today() - timedelta(days=14)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM