1

我正在尝试在 django 模型方法中传递timezone.now() + timedelta(days=-2)和作为参数,但我得到了timezone.now()

def performance(user, timezone.now() + timedelta(days=-2), timezone.now()):
                                  ^
SyntaxError: invalid syntax

我知道错误是由于串联造成的,但我不知道如何解决这个问题。

class User(AbstractUser):
    .........................
    fields
    .........................

    def get_performance(self, timezone.now() + timedelta(days=-2), timezone.now()):

        actual = Sum("scores", filter=Q(status="completed"))

        q = self.taskassignt.filter(
            due__gte=timezone.now() + timedelta(days=-2),
            due__lt=timezone.now() 
        ).annotate(actual=actual, total=Sum("scores"))

        return (q[0].actual / q[0].total) * 100
4

1 回答 1

1

您需要指定一个参数名称,所以

def get_performance(self, start_time=timezone.now() + timedelta(days=-2), end_time=timezone.now()):
    actual = Sum("scores", filter=Q(status="completed"))
    q = self.taskassignt.filter(
        due__gte=start_time,
        due__lt=end_time 
    ).annotate(actual=actual, total=Sum("scores"))

    return 100 * q[0].actual / q[0].total

但这不起作用,因为默认值将被初始化一次,然后每次都使用。这意味着如果您的服务器运行一整年,start_time仍将是上一年的时间。

通常使用 aNone作为默认值,如果参数确实是None,则将其替换为给定的表达式,因此:

def get_performance(self, start_time=None, end_time=None):
    if start_time is None:
        start_time = timezone.now() + timedelta(days=-2)
    if end_time is None:
        end_time = timezone.now()
    actual = Sum("scores", filter=Q(status="completed"))
    q = self.taskassignt.filter(
        due__gte=start_time,
        due__lt=end_time 
    ).annotate(actual=actual, total=Sum("scores"))

    return 100 * q[0].actual / q[0].total

然而,拥有一个100 * q[0].actual / q[0].total. 这意味着你只对第一个 taskassignt感兴趣,而不是全部。您可能想要.aggregate(…)[Django-doc]而不是.annotate(…)[Django-doc]

def get_performance(self, start_time=None, end_time=None):
    if start_time is None:
        start_time = timezone.now() + timedelta(days=-2)
    if end_time is None:
        end_time = timezone.now()
    actual = Sum("scores", filter=Q(status='completed'))
    q = self.taskassignt.filter(
        due__gte=start_time,
        due__lt=end_time 
    ).aggregate(actual=actual, total=Sum("scores"))

    return 100 * q['actual'] / q['total']
于 2021-09-11T16:20:43.837 回答