Python 基于列表的过滤搜索
再一次,可能是另一个noob django问题。我的django应用程序中有这两个模型Python 基于列表的过滤搜索,python,django,django-models,django-views,Python,Django,Django Models,Django Views,再一次,可能是另一个noob django问题。我的django应用程序中有这两个模型 #models.py class Question(models.Model): group = models.ManyToManyField(Groups) test = models.ForeignKey(Test, on_delete=models.CASCADE) question = models.TextField(max_length=1000) def __s
#models.py
class Question(models.Model):
group = models.ManyToManyField(Groups)
test = models.ForeignKey(Test, on_delete=models.CASCADE)
question = models.TextField(max_length=1000)
def __str__(self):
return "{0}".format(self.question)
class Answer(models.Model):
question = models.ForeignKey(Question)
answer = models.TextField(max_length=1000)
correct = models.BooleanField()
def __str__(self):
return "{0}".format(self.answer)
我还有一个与这两个模型交互的视图
#views.py
def test_detail(request, pk):
test = get_object_or_404(Test, pk=pk)
questions = Question.objects.values('id', 'question').filter(test_id=pk).order_by('?')
answers = Answer.objects.values('answer').filter(question_id__in=list(questions))
return render(request, 'site/test.html', {'test': test, 'questions': questions, 'answers': answers})
“问题”是所有问题对象都有一个id的列表。该id也是答案中的外键。我要做的是获取所有答案对象,这些对象的id与“问题”列表中的任何id相同
但是,这种方法会抛出一个TypeError:int()参数必须是字符串、类似字节的对象或数字,而不是“dict”
有人能帮我指出我做错了什么吗?你能不能不通过
question\uu in=questions
进行筛选?你想得到与问题id相同的答案列表?这听起来很奇怪。。。。更可能的情况是,您正在查找Question.objects.filter(test\u id=pk)。prefetch\u related('answer')
列表(问题)
是问题
对象的列表,而不是问题.id
。使用列表理解,如[q.id for q in questions]
从问题中获取id列表。@kicker86一般经验法则是不使用python迭代进行数据库查询。类似于上面的注释更有效。@kicker86-list(questions)
是一个字典列表,因为op使用值