Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a queryset for dates matching a given day?

I am trying to build a query for a view in Django in which I want to retrieve rows with today date (no matter the time).

I was thinking in a range between current date and datetime.datetime.now()

However I can't get only the date but not the time.

I have this:

now = datetime.datetime.now()
today = datetime.datetime.today()
var = Example.objects.filter(date__gt=datetime.date(today.year(), today.month(), today.day()), fecha__lt=now)
like image 693
Kookoriko Avatar asked Feb 20 '14 20:02

Kookoriko


People also ask

Can you filter a QuerySet?

Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.

What is Django filter?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this. Adding a FilterSet with filterset_class. Using the filterset_fields shortcut.


2 Answers

today = datetime.datetime.today()
Example.objects.filter(
    date__year=today.year, 
    date__month=today.month, 
    date__day=today.day
)
like image 52
wim Avatar answered Sep 29 '22 17:09

wim


Grab rows that have a create date greater than the current date using only the date() method of the datetime.now() class.

where row.createdate > datetime.datetime.now().date()
like image 32
Moe Khalil Avatar answered Sep 29 '22 17:09

Moe Khalil