0

I have a DateTimeField named created_at in my model. I Would like to query the objects which are created today. From this question I have used the following query set,

In [70]: today = datetime.datetime.today().date()
In [72]: Business.objects.filter(created_at__date=today)
Out[72]: <QuerySet []>

It returns zero results. I have make sure that there is an entry in the database, which was created today. I know that I can also use

Business.objects.filter(created_at__contains=today)

But it yields results with a warning:

django/db/backends/mysql/base.py:71: Warning: (1292, "Incorrect datetime value: '%2017-12-21%' for column 'created_at' at row 1")

I'm using MySQL database. My Model is

class Business(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True)
    url = models.CharField(max_length=255, blank=True, null=True)
    created_at = models.DateTimeField()
    category = models.CharField(max_length=120)

    class Meta:
        managed = False
        db_table = 'Business'
        unique_together = (('name', 'url'),)
Arun
  • 1,933
  • 2
  • 28
  • 46

2 Answers2

1
from django.utils import timezone
Business.objects.filter(created_at__gte=timezone.now())

i guess this will be better for you.

and change your model

created_at = models.DateTimeField(auto_now=True)

then makemigrations, migrate and then add some data and try again

Exprator
  • 26,992
  • 6
  • 47
  • 59
  • It shows a warning `RuntimeWarning: DateTimeField Business.created_at received a naive datetime (2017-12-21 05:28:17.113688) while time zone support is active.` but there are no results. – Arun Dec 21 '17 at 05:29
  • do you have any data of today?? 21-12-2017 and try the edited ans once – Exprator Dec 21 '17 at 05:31
  • Still not getting. I have an object created today. `b = Business.objects.get(id=4)`. `b.created_at` prints `datetime.datetime(2017, 12, 21, 9, 53, 31, tzinfo=)` – Arun Dec 21 '17 at 05:33
  • Edited. The models has generated by using `inspectdb` command. – Arun Dec 21 '17 at 05:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161678/discussion-between-arun-and-exprator). – Arun Dec 21 '17 at 06:17
  • Sure, with pleasure. – Arun Dec 22 '17 at 03:59
0

Use timezone library

today = timezone.datetime.today().date()

else

today = timezone.now().date()
vinayak
  • 34
  • 8
  • It's not working.Even `Business.objects.filter(created_at__date=datetime.date(2017, 12, 21))` does not yield results. – Arun Dec 21 '17 at 05:21
  • Try to print the result in console first and checkout the data in "today" – vinayak Dec 21 '17 at 05:24
  • check the data type. In case of any miss match you wont get the desired result – vinayak Dec 21 '17 at 05:25
  • `today` is `datetime.date(2017, 12, 21)` and the DateTimeField in object is `datetime.datetime(2017, 12, 21, 9, 53, 31, tzinfo=)` – Arun Dec 21 '17 at 05:27