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

问题描述 投票:0回答:1

我有两个这样的模型:

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()

我需要执行此查询以获取正确的'ques'字段值。

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')

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

python django
1个回答
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')
© www.soinside.com 2019 - 2024. All rights reserved.