0

In model.py, I create class Order has a field 'order_date' with DateTimeField.

In views.py, I am using this query:

orders = Order.objects.filter(order_date__date__gte = date_from, order_date__date__lte = date_to)

The Query doesn't return any data, although in the database, there are many records between date_from and date_to.

tnductam
  • 397
  • 4
  • 10
  • 2
    can you post the date_from and date_to codes, how are you taking it – Exprator Nov 30 '17 at 07:35
  • you have typo in `order_day__date__gte` it should be `order_date__date__gte` – Satendra Nov 30 '17 at 07:39
  • @Satendra, I fixed, change `order_day` into `order_date` but I still receive my result I want. – tnductam Nov 30 '17 at 08:27
  • use `date_from.date()` and `date_to.date()` inspite of `date_from` and `date_to` in query, let me know if this works? – Satendra Nov 30 '17 at 08:31
  • 1
    Possible duplicate of [Django database query: How to filter objects by date range?](https://stackoverflow.com/questions/4668619/django-database-query-how-to-filter-objects-by-date-range) – Clément Denoix Nov 30 '17 at 08:46
  • @Satendra, I use the query: `orders = Order.objects.filter(order_date__date__gte = date_from.date(), order_date__date__lte = date_to.date())` I have an error: **'datetime.date' object has no attribute 'date'**, although I add `from datetime import date` – tnductam Nov 30 '17 at 09:32

1 Answers1

0

You can do that like this:

orders = Order.objects.filter(order_date__gte = date_from, order_date__lte = date_to)

You have an extra __date that you don't need, since order_date is a DateTimeField.

Dalvtor
  • 3,160
  • 3
  • 21
  • 36
  • If I don't use `__date`, when I set `date_from` is '11/30/2017', in the query `date_from` will set 11/30/2017 00:00:00'. And `date_to` is the same. – tnductam Nov 30 '17 at 09:27
  • are date_from and date_to strings or date objects? – Dalvtor Nov 30 '17 at 09:31
  • I use `if date_from_str and date_to_str: date_from = getDateFromString(date_from_str) date_to = getDateFromString(date_to_str) else: date_from = datetime.date.today() date_to = datetime.date.today()` to get date. – tnductam Nov 30 '17 at 09:33