我正在尝试从ManyToManyField模型中获取数据。我在manytomanyfield中有两个模型问题和quiz_spes我试图访问特定quiz_spec的所有问题 我的模型如下。我的模型正在关注
class quiz_spec(models.Model):
title=models.TextField()
course = models.ForeignKey(Course)
start_date = models.DateField()
end_date = models.DateField()
duration = models.IntegerField()
credit=models.IntegerField()
def __str__(self):
return self.title
和问题模型是
class question(models.Model):
CHOICES = (
('option 1','a'),
('option 2','b'),
('option 3','c'),
('option 4','d'),
)
statement = models.TextField()
a = models.TextField()
b = models.TextField()
c = models.TextField()
d = models.TextField()
addedBY=models.ForeignKey(faculty_profile,null=True)
ans = models.CharField(max_length=1,choices=CHOICES)
category=models.TextField()
extra_info=models.TextField()
quizes = models.ManyToManyField(quiz_spec,blank=True,null=True)
dateAdded = models.DateTimeField(auto_now=True);
我的观点是
def quiz_confirm(request):
quiz=quiz_spec.objects.get(id=request.session['quiz_id'])
print request.session['quiz_id']
print quiz
try:
questions=question.objects.all().filter(quizes=quiz)
except Exception as e:
print e
print questions
return render(request, 'quiz_confirm.html')
它给[]输出。但是测验不是空的。
答案 0 :(得分:1)
您是否尝试过查询以下问题:
questions = question.objects.filter(quizes__in=[quiz])
或者您可以通过查询从测验方面获得问题:
questions = quiz.question_set.all()
应返回与测验相关的所有问题。
答案 1 :(得分:0)
你应该使用
questions = question.objects.filter(quizes__contains=quiz)