我有以下方案:
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
,所需contest
和is_solved
设置为True的数量。如何进行这样的查询?
答案 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
,因为否则某些实例可能会用IntegerField
和True
注释,以防零个或一个用户解决。