开发者

how to filter by date with datetimefield in Django with MYSQL

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜