开发者

how to filter by date with datetimefield in Django with MYSQL

开发者 https://www.devze.com 2022-12-07 18:22 出处:网络
Datetimefield in MYSQL cannot be filtered by date. class Data(models.Model): created_at = models.DateTimeField(default=timezone.now)

Datetimefield in MYSQL cannot be filtered by date.

    class Data(models.Model):
        created_at = models.DateTimeField(default=timezone.now)

As docs, it could be filtered by date:

  qs = Data.objects.fitler(created_at__date__lte=datetime.date(2022, 1, 1))

It works fine wit开发者_开发知识库h sqlite3, but it always return empty queryset with MYSQL.


First you need to convert the date to a datetime object. In your case convert '2022-01-01' as:

from datetime import datetime

date_object = datetime.strptime("2022-01-01", "%Y-%m-%d")

# Then you can filter it as
qs = Data.objects.fitler(created_at__date__lte=date_object)

0

精彩评论

暂无评论...
验证码 换一张
取 消