I understand this particular error message
'QuerySet' object has no attribute '_meta'
has been discussed a lot on StackOverflow and I have gone through lots of the answers provided but each is unique and didn't solve my problem.
So, I have a list of filtered model objects I'm getting from a database:
questions_by_category = Question.objects.filter(category=category_id)
I want to save this list in the session like this:
request.session["questions"] = json.dumps(model_to_dict(questions_by_category))
but I'm getting the error message specifically from this line:
model_to_dict(questions_by_category)
This is the model class:
class Question(models.Model):
question_text = models.CharField(max_length=200)
correct_answer = models.CharField(max_length=20)
publication_date = models.DateTimeField('date_published', default=django
.utils.timezone.now)
question_hint = models.CharField(max_length=200, default='hint')
question_thumbnail = models.ImageField(upload_to='gallery', height_field=None, width_field=None,
max_length=100,
default='images/pyramid.jpg')
category = models.ForeignKey(QuestionCategory, on_delete=models.SET_NULL, null=True)
difficulty_level = models.IntegerField(default=10)
def was_published_recently(self):
return self.publication_date >= timezone.now() - datetime.timedelta(days=1)
class Meta:
db_table = 'question'
def __str__(self):
return self.question_text
def serialize(self):
return self.__dict__
And the view:
def question(request, category_name, category_id):
questions_by_category = Question.objects.filter(category=category_id)
current_question = questions_by_category.iterator().__next__()
choice = current_question.choice_set.get()
form = ChoiceForm(request.POST)
request.session["questions"] = json.dumps(model_to_dict(questions_by_category))
context = {
'question': current_question, 'choice': choice, 'form': form
}
return render(request, 'quiz/question.html', context)
EDIT
This the other view where I intend to modify the list:
def accept_choice(request):
global data
if request.method == 'POST':
data = request.POST.get('choiceRadioGroup')
print('Selected data: ' + str(data))
return render(request, 'quiz/question.html', {'data': 'data'}
The goal here (which is starting to appear messy) is to select accept a choice from the question view, on next button click, accept_choice is called, and the next question id displayed. My intention is to keep track of the current question by maintaining the list of questions in a session.
I'd really appreciate an explanation on what I'm doing wrong and the right way to go about this.