我有两个模型Assessment
和Answer
与OnetoMany关系。
models.py
class Assessment(models.Model):
name = models.CharField(max_length=255, blank=False)
def __str__(self):
return "{}".format(self.name)
def _all_answers_completed(self):
pass
#some how get all related answers
#then see if "completed" = true
#if all = true then return true
#if any = false then return false
completed = property(_all_answers_completed)
class Answer(models.Model):
assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.CASCADE)
score_risk = models.IntegerField(default=0)
score_impact = models.IntegerField(default=0)
score_occurrance = models.IntegerField(default=0)
def __str__(self):
return "Answer to Question:{} for Assessment {}".format(self.question, self.assessment)
def _is_answered(self):
if self.score_risk > 0 and self.score_impact >0 and self.score_occurrance > 0:
return True
else:
return False
completed = property(_is_answered)
我想根据相关答案属性completed
answer.completed
我只是不知道如何执行此操作,或者我必须通过循环查询集在视图中执行此操作。
答案 0 :(得分:2)
您可以获得与当前“评估”对象相关的所有“答案”,然后循环浏览它们以查找是否所有答案都已完成。
您的代码应该与此类似(未经测试):
self.answer_set
此处Answer
将获取具有当前Assesment
对象的外键(即self
)的所有{{1}}个对象。您可以详细了解here和here
答案 1 :(得分:1)
您可以使用backward-related-objects。