用django-polymorphic检索相关的多态集

时间:2017-12-07 12:49:11

标签: django django-queryset

我有三个简单的模型:

class Employee(models.Model):
    [...]


class AttendanceLog(models.Model):
    employee = models.ForeignKey(Employee, [...])
    from_datetime = models.DateTime([...])
    to_datetime = models.DateTime([...])


class Salary(models.Model):
    employee = models.ForeignKey(Employee, [...])
    [...]

我需要的是提出一个查询,该查询将返回员工上班(出勤)的总时间(SUM)。我现在拥有的:

# method in Salary
def get_attended_hours(self):
    qs = AttendanceLog.objects.employee(self.employee).filter(to_datetime__year=self.year, to_datetime__month=self.month)
    qs = qs.values('employee') # group by employee (should not be needed)
    duration = ExpressionWrapper(F('to_datetime') - F('from_datetime'), output_field=fields.DurationField())
    qs = qs.annotate(duration=Sum(duration)).values_list('duration', flat=True)

    # expected output: {'duration': datetime.timedelta(0, x)}
    # actual output: <AttendanceLogQuerySet [datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 3600), datetime.timedelta(0, 14400), datetime.timedelta(0, 10800), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), '...(remaining elements truncated)...']>

    # qs.query: SELECT SUM(django_timestamp_diff("human_resources_attendancelog"."to_datetime", "human_resources_attendancelog"."from_datetime")) AS "duration" FROM "human_resources_attendancelog" WHERE ("human_resources_attendancelog"."employee_id" = 22 AND "human_resources_attendancelog"."to_datetime" BETWEEN 2017-01-01 00:00:00 AND 2017-12-31 23:59:59.999999 AND django_datetime_extract('month', "human_resources_attendancelog"."to_datetime", None) = 11 AND "human_resources_attendancelog"."attendance_type" = RE) GROUP BY "human_resources_attendancelog"."employee_id", "human_resources_attendancelog"."to_datetime" ORDER BY "human_resources_attendancelog"."to_datetime" ASC

    # problematic part: GROUP BY "human_resources_attendancelog"."employee_id", "human_resources_attendancelog"."to_datetime"

基本上,为什么它还在GROUP BY上使用to_datetime?我尝试使用GROUP BY强制qs.values('employee')子句,但这并不会删除to_datetime。此查询集上不应该有GROUP BY,因为我们已经根据需要过滤了数据。 (由于业务逻辑原因,我不想按年或月来GROUP BY。)

基本上问题是我需要SUM

0 个答案:

没有答案