具有多个外键的Django查询似乎不起作用

时间:2019-02-11 06:07:46

标签: python django orm foreign-keys

我正在尝试从表Answer中获取一条记录,该记录对应于外键学习者和问题。问题外键虽然没有给出。结果可用。我似乎无法使我的查询正常工作。有人可以指出我做错了什么吗?

#Model classes:
class Answer(models.Model):
    problem = models.ForeignKey('Problem', on_delete=models.CASCADE,
        blank=False, help_text="Problem ID")
    learner = models.ForeignKey('Learner', on_delete=models.CASCADE,
        blank=False, help_text="Learner ID")
    try_count = models.IntegerField(blank=False, default=0,
        help_text="Number of times the problem was attempted")
    correct = models.CharField(max_length=1, blank=False, default='0',
        choices=Constant.CORRECT,
        help_text="Indicator whether the problem was answered correctly or not")
    ...

class Problem(models.Model):
    outcome = models.ForeignKey('Outcome', on_delete=models.CASCADE,
        blank=False, help_text="Outcome ID")
    ...

class Outcome(models.Model):
    name = models.CharField(max_length=32, blank=False, unique=True,
        help_text="Outcome name")
    ...

class Learner(models.Model):
    anonymous_id = models.CharField(max_length=32, blank=False,
        help_text="Anonymous ID")
    ...

# Query
answer = Answer.objects.filter(learner=learner,
    problem__outcome=outcome).order_by('correct', 'try_count')[0]

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您将结果作为ID,而不将结果作为对象。如果是这种情况,请尝试将查询更改为以下内容:

answer = Answer.objects.filter(learner=learner,
problem__outcome__id=outcome).order_by('correct', 'try_count')[0]

如果您将学习者作为ID,将结果作为ID,请尝试以下操作:

answer = Answer.objects.filter(learner__id=learner,
problem__outcome__id=outcome).order_by('correct', 'try_count')[0]

请注意,我在学习者和结果之后添加了__id。