如何连接具有多个外键的表并在Django中获取过滤数据?

时间:2018-01-26 18:35:15

标签: python django

我有两个这样的模型:

class Question(models.Model):
        ques_id = models.IntegerField()
        test_id = models.ForeignKey('exam.Test')
        ques = models.TextField()

class UserAnswer(models.Model):
        user = models.ForeignKey('exam.User')
        test_id = models.ForeignKey('exam.Test')
        ques_id=models.ForeignKey('exam.Question')
        user_ans = models.TextField()

我需要执行此查询才能获得正确的问题'字段值。

SELECT A.ques_id, B.ques, A.user_ans FROM useranswer A
inner join question B on B.ques_id= A.ques_id and B.test_id =A.test_id
WHERE A.user_id=1 and B.test_id='101'

到目前为止,我所做的一切:

UserAnswer.objects.filter(test_id=test_id, user_id=user_id).values('ques_id', 'ques_id__ques','user_ans')

但它并没有回复正确的问题'字段值,因为它没有考虑B.test_id = A.test_id部分。如何检索???

1 个答案:

答案 0 :(得分:0)

首先,您的字段名称具有误导性。 _id的后缀外键字段!将它们作为属性访问会返回模型实例,而django会提供_id后缀属性来隐式访问实际的键:

class Question(models.Model): 
    test = models.ForeignKey('exam.Test')
    ques = models.TextField()
    # is this supposed to be the primary key? Don't do that
    # ques_id = models.IntegerField() 

class UserAnswer(models.Model):
    user = models.ForeignKey('exam.User')
    ques = models.ForeignKey('exam.Question')
    user_ans = models.TextField()
    # This is redundant as ques belongs to a test already
    # test = models.ForeignKey('exam.Test')  

我假设你想得到一个用户和一个测试的所有答案:

UserAnswer.objects.filter(
    ques__test_id=test_id, 
    user_id=user_id
).values('ques_id', 'ques__ques', 'user_ans')