Django模型方法计算外键的方法标志

时间:2017-12-06 17:52:07

标签: django django-models django-views

我有两个模型AssessmentAnswer与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

我只是不知道如何执行此操作,或者我必须通过循环查询集在视图中执行此操作。

2 个答案:

答案 0 :(得分:2)

您可以获得与当前“评估”对象相关的所有“答案”,然后循环浏览它们以查找是否所有答案都已完成。

您的代码应该与此类似(未经测试):

self.answer_set

此处Answer将获取具有当前Assesment对象的外键(即self)的所有{{1}}个对象。您可以详细了解herehere

答案 1 :(得分:1)

您可以使用backward-related-objects