【问题标题】:Django filter datetime with timezone field with date onlyDjango过滤日期时间与时区字段仅日期
【发布时间】:2022-08-22 22:50:27
【问题描述】:

我在 django 模型中有一个字段:“created_at”,它是带有时区的日期时间(例如:2022-08-09 14:03:18.467482+02)。在我的应用程序中,我有一个表单,用户仅选择日期(例如:2022-06-09)。

我试图在我的视图中过滤该字段,如下所示:

res = MyObject.objects.all()
res = res.filter(created_at = date)

我收到以下错误:RuntimeWarning: DateTimeField Mybject.created_at received a naive datetime (2022-06-09 00:00:00) while time zone support is active.

用用户输入日期过滤我的对象的最佳方法是什么?我是否需要将时区添加到用户选择的日期以及如何添加?

    标签: python django


    【解决方案1】:

    设法解决这个问题,正确的语法是像这样添加双下划线:

    res = res.filter(created_at__date = date)
    

    【讨论】:

      【解决方案2】:

      尝试将.date() 添加到 Created_at 它应该将时区对象转换为日期

      【讨论】:

      • 不是 'dot' date() 这是数据库 DateTimeField ,它想用时区获取时间。我们不在过滤函数的 kwargs 中使用 'dot' 表示法。 created_at__date 是正确答案。
      【解决方案3】:

      日期时间具有属性created_at.datecreated_at.time

      res = MyObject.objects.filter(created_at__date=date)
      

      【讨论】:

      • 这会破坏代码并出现以下错误SyntaxError: expression cannot contain assignment, perhaps you meant "=="?。如果我将其更改为 == ,我会得到 NameError: name 'created_at' is not defined
      猜你喜欢
      • 2015-03-06
      • 2014-03-31
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 2018-01-25
      • 2020-11-27
      相关资源
      最近更新 更多