Django [SOLVED]: Django DateTimeField date filter not working

Django [SOLVED]: Django DateTimeField date filter not working

Home Forums Frameworks Django Tutorials Django [SOLVED]: Django DateTimeField date filter not working

Tagged: , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #246349

    Cloudy Point
    Keymaster

    QuestionQuestion

    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'),)
    

    #246350

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    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

    Source: https://stackoverflow.com/questions/47918295/django-datetimefield-date-filter-not-working
    Author: Exprator
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.