注释中间模型django的字段

时间:2018-06-26 08:53:53

标签: django many-to-many django-queryset

我有以下方案:

class User(AbstractUser):
    pass

class Task(models.Model):
    pass

class Contest(models.Model):
    tasks = models.ManyToManyField('Task',
                               related_name='contests',
                               blank=True,
                               through='ContestTaskRelationship')

    participants = models.ManyToManyField('User',
                                      related_name='contests_participated',
                                      blank=True,
                                      through='ContestParticipantRelationship')

class ContestTaskRelationship(models.Model):
    contest = models.ForeignKey('Contest', on_delete=models.CASCADE)
    task = models.ForeignKey('Task', on_delete=models.CASCADE)
    cost = models.IntegerField()


class ContestParticipantRelationship(models.Model):
    contest = models.ForeignKey('Contest', on_delete=models.CASCADE)
    user = models.ForeignKey('User', on_delete=models.CASCADE)
    task = models.ForeignKey('Task', on_delete=models.CASCADE, related_name='contests_participants_relationship')
    is_solved = models.BooleanField()

现在,我得到了contest对象,并且需要获取tasks字段上的所有任务,并用用户数注释的rach解决了该问题。因此,我需要计算ContestParticipantRelationship,所需task,所需contestis_solved设置为True的数量。如何进行这样的查询?

1 个答案:

答案 0 :(得分:0)

可能类似于:

private Path asDirectoryPath(Path filePath) {
    return Paths.get(filePath.getParent());
}

因此,在此我们首先过滤任务竞赛为from django.db.models import IntegerField, Value, Sum from django.db.models.functions import Cast, Coalesce Task.objects.filter( contests__contest=some_contest, ).annotate( nsolved=Cast(Coalesce( Sum('contests_participants_relationship__is_solved'), Value(0) ),IntegerField()) ) 的事实。接下来,我们在some_contest列上执行Sum(..)。由于在某些极端情况下可以使用is_solved(如果没有用户进行尝试等),那么我们将其转换为NULL,然后将其转换为0,因为否则某些实例可能会用IntegerFieldTrue注释,以防零个或一个用户解决。