【问题标题】:Django getting only the most recent object after filteringDjango过滤后只获取最新的对象
【发布时间】:2012-09-10 09:04:17
【问题描述】:

我正在为 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 任何问题,我只想看到最近的一个

【问题讨论】:

  • 你的表中是否有插入时间作为列?
  • 您还想存储以前的答案吗?如果没有,那么当您为 QuestionAnswer 创建模型表单时,请使用现有实例,以便在您保存表单时更新该实例。
  • 不,我没有插入时间,但可以轻松添加,我正在考虑使用主键来确定最近的答案。 @Rohan 是的,我想保留答案的审计线索。
  • @Ctrlspc 好的,然后很容易通过latest(your_datetime_field) 过滤。靠PK来测序不好。
  • 我怀疑您可能需要更改模型,这个问题可能会有所帮助stackoverflow.com/questions/3483307/…

标签: python django django-models


【解决方案1】:

感谢@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>)]  

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2010-12-07
    • 2013-05-06
    • 2014-05-19
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多