【问题标题】:Combine Date and Time in Django Queryset - TypeError在 Django 查询集中结合日期和时间 - TypeError
【发布时间】:2019-03-20 08:06:10
【问题描述】:

我正在尝试使用 annotate 在我的 Django 查询集中组合日期和时间。

TimesheetEntry.objects.exclude(
    timesheet_is_running = False
).filter(
    timesheet_users__userprofile__user_company=request.user.userprofile.user_company
).annotate(
    timesheet_clock_in_time_date=datetime.datetime.combine('timesheet_clock_in_date', 'timesheet_clock_in_time')
).values_list(
    'timesheet_jobs__job_number',
    'timesheet_clock_in_time_date',
)

但它给了我TypeError

combine() 参数 1 必须是 datetime.date,而不是 str

【问题讨论】:

    标签: django


    【解决方案1】:

    您没有提供日期和时间值来组合功能,您只是提供字符串 'timesheet_clock_in_date''timesheet_clock_in_time' 作为组合功能的参数。要在数据库中进行合并操作,您需要将 F 表达式与 ExpressionWrapper 一起使用。您可以在official docs 中找到有关这些的更多信息。基本上,您需要以下内容:

    TimesheetEntry.objects.exclude(
        timesheet_is_running = False
    ).filter(
        timesheet_users__userprofile__user_company=request.user.userprofile.user_company
    ).annotate(
        timesheet_clock_in_time_date=ExpressionWrapper(
            F('timesheet_clock_in_date')+ F('timesheet_clock_in_time'),
            output_field=DateTimeField()
        )
    ).values_list(
        'timesheet_jobs__job_number',
        'timesheet_clock_in_time_date',
    )
    

    【讨论】:

      猜你喜欢
      • 2013-12-23
      • 1970-01-01
      • 2012-10-14
      • 2013-02-27
      • 2020-05-08
      • 2021-01-05
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      相关资源
      最近更新 更多