0

我正在为 Django 开发一个问卷类型的应用程序。当参与者完成调查问卷时,将创建一个 AnswerSet 对象,该对象将他们的用户对象链接到 QuestionAnswer 对象列表,他们回答的每个问题都有一个。

class AnswerSet(models.Model):

    user=models.ForeignKey(User)
    questionnaire=models.ForeignKey(Questionnaire)


class QuestionAnswer(models.Model):    

    question = models.ForeignKey(Question)
    answer = models.CharField(max_length=255)
    answer_set = models.ForeignKey(AnswerSet)

该应用程序允许人们重新回答问卷,在这种情况下,使用他们现有的答案呈现表单,对于更新的答案,创建并保存一个新的 QuestionAnswer 对象。

因此,我的问题是:

为了在参与者编辑问卷时显示最新的答案,我希望能够获得一个 AnswerSet,然后过滤 QuestionAnswers 以便我为每个问题获得一个 QuestionAnswer,并且有多个 QuestionAnswer 用于任何问题,我只想看最近的一个

4

1 回答 1

0

感谢@Rohan 的建议和这篇文章Django query select distinct by field pairs我找到了一个适合我的解决方案,希望其他人也会觉得它有用!我添加了一个新模型:

class LatestQuestionAnswer(models.Model):
    question = models.ForeignKey(Question)
    question_answer = models.ForeignKey(QuestionAnswer)
    answer_set = models.ForeignKey(AnswerSet)
    created = created = models.DateTimeField(auto_now_add=True)

并覆盖了我的 QuestionAnswerModel 上的保存功能,所以它看起来像:

def save(self, force_insert=False, force_update=False, using=None):
        super(QuestionAnswer, self).save(force_insert=force_insert, force_update=force_update, using=using)

        try:
            record = LatestQuestionAnswer.objects.get(question=self.question, answer_set=self.answer_set)

            if record.question_answer == self:
                return#nothing to do no point updating the record as it is already correct

        except ObjectDoesNotExist:
            record = LatestQuestionAnswer(question=self.question, answer_set= self.answer_set)

        record.question_answer = self
        record.save()

现在,每当我需要获取所有最新 QuestionAnswers 的列表时,我都可以执行以下操作:

most_recent_answers = [record.question_answer for record in LatestQuestionAnswer.objects.filter(answer_set=<an_answer_set>)]  
于 2012-09-10T15:15:33.320 回答