How can I filter a date of a DateTimeField in Django?

Such lookups are implemented in django.views.generic.date_based as follows: {‘date_time_field__range’: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} Because it is quite verbose there are plans to improve the syntax using __date operator. Check “#9596 Comparing a DateTimeField to a date is too hard” for more details.

Django values_list vs values

The values() method returns a QuerySet containing dictionaries: <QuerySet [{‘comment_id’: 1}, {‘comment_id’: 2}]> The values_list() method returns a QuerySet containing tuples: <QuerySet [(1,), (2,)]> If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples: <QuerySet [1, 2]>

How do I get the object if it exists, or None if it does not exist in Django?

There is no ‘built in’ way to do this. Django will raise the DoesNotExist exception every time. The idiomatic way to handle this in python is to wrap it in a try catch: try: go = SomeModel.objects.get(foo=’bar’) except SomeModel.DoesNotExist: go = None What I did do, is to subclass models.Manager, create a safe_get like the … Read more

How do I filter query objects by date range in Django?

Use Sample.objects.filter(date__range=[“2011-01-01”, “2011-01-31″]) Or if you are just trying to filter month wise: Sample.objects.filter(date__year=”2011″, date__month=”01”) Edit As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).