Dave Merwin
Dave Merwin

Reputation: 1412

Django select an object based on a date

This is driving me crazy. I've used all the lookup_types and none seem to work.

I need to select an object that was created two weeks ago from today.

Here's what I've got:

twoweeksago = datetime.datetime.now() - datetime.timedelta(days=14)
pastblast = Model.objects.filter(user=user, created=twoweeksago, done=False)

The model has a created field that does this: created = models.DateTimeField(auto_now_add=True, editable=False)

But my query isn't returning everything. Before you ask, yes, there are records in the db with the right date.

Can someone make a suggestion as to what I'm doing wrong?

Thanks

Upvotes: 0

Views: 466

Answers (1)

JoseP
JoseP

Reputation: 631

DateTimeField is very different from DateField, if you do

twoweeksago = datetime.datetime.now() - datetime.timedelta(days=14)

That is going to return today's date, hour, minute, second minus 14 days, and the result is going to include also hours minutes seconds etc. So the query:

pastblast = Model.objects.filter(user=user, created=twoweeksago, done=False)

Is going to find for a instance was created just in that exact time, If you only want to care about the day, and not hours, minutes and seconds you can do something like

pastblast = Model.objects.filter(user=user, created__year=twoweeksago.year, created__month=twoweeksago.month, created__day=twoweeksago.day, done=False)

Check the django docs: https://docs.djangoproject.com/en/1.4/ref/models/querysets/#year

Upvotes: 3

Related Questions