在Django Queryset中合并日期和时间-TypeError

时间:2019-03-20 08:06:11

标签: django

我正在尝试使用annotate在Django Queryset中组合日期和时间。

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

1 个答案:

答案 0 :(得分:3)

您没有提供要组合功能的日期和时间值,只是提供了字符串'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',
)