[英]django queryset cannot run function inside annotate and Sum
I have two queryset and I want to do Addition from those two queryset but one query value are Int type (eg 1.5, 2.75 ) but others have time like string (eg 12:20:59). 我有两个查询集,我想从这两个查询集进行加法运算,但是一个查询值是Int类型(例如1.5、2.75),但是其他查询时间像字符串(例如12:20:59)。 I need to convert that string to Int type so I can do use Sum Function in Annotate. 我需要将该字符串转换为Int类型,以便可以在Annotate中使用Sum Function。
First queryset 第一个查询集
timesheet_total_by_project = TimesheetEntry.objects.filter(
created_by_id=current_user,
timesheet__for_date__gte=start_tim,
timesheet__for_date__lte=end_date,
project__is_visible=True
).values(
'project__name', 'project__id'
).distinct().annotate(totalsum=Sum('minutes', output_field=FloatField()) / 60.0)
2nd Queryset 第二查询集
ticket_total_time = Ticket.objects.filter(
assigned_to=user, total_time__isnull=False, project__is_visible=True
).values(
'title','project__id'
).distinct().annotate(totalsum=Sum('total_time', output_field=FloatField()) / 60.0)
I have tried 我努力了
def get_sec(time_str):
print("string",time_str)
"""Get Seconds from time."""
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
ticket_total_time = Ticket.objects.filter(assigned_to=user,total_time__isnull=False,project__is_visible=True).values('title','project__id').distinct().annotate(totalsum=Sum(get_sec('total_time'), output_field=FloatField()) / 3600.0)
Expected Output is would be 12.5 but output for print("string",time_str) 预期输出为12.5,但输出为print(“ string”,time_str)
string total_time
Also says 还说
ValueError: not enough values to unpack (expected 3, got 1)
def get_sec(time_str):
print(f'{time_str = }')
"""Get Seconds from time."""
if not time_str:
return 0
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
MySQL has a STR_TO_DATE
function that will convert a string to a date. MySQL具有STR_TO_DATE
函数,该函数会将字符串转换为日期。 You can run arbitrary database functions with a Func
expression : 您可以使用Func
表达式运行任意数据库函数:
from django.db.models import F, Func, Value
ticket_total_time = Ticket.objects.filter(
assigned_to=user, total_time__isnull=False, project__is_visible=True
).values(
'title','project__id'
).distinct().
annotate(time_t=Func(F('total_time'), Value('%H:%i:%s'), function='STR_TO_DATE')).
annotate(totalsum=Sum('time_t', output_field=FloatField()) / 60.0)
I tried this solution and it work fine. 我尝试了这种解决方案,它工作正常。 Now Time_to_sec function is working inside annotate. 现在,Time_to_sec函数正在内部注释中。
from django.db.models import F, Func
class Time_to_sec(Func):
function = 'TIME_TO_SEC'
lookup_name = 'sec'
ticket_total_time = Ticket.objects.filter(assigned_to=user,total_time__isnull=False,project__is_visible=True).values('project__id').distinct().annotate(totalsum=Sum(Time_to_sec('total_time', output_field=FloatField()) / 3600.0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.