我想在对象中添加属性,其中包括m2m。
models.py
class GamerQuestion(models.Model):
gamer = models.ForeignKey(User)
question = models.ManyToManyField(Question)
test = models.ForeignKey(Test)
view.py
for question in context['object_list'].question.all():
question.foo = 'add_info'
for question in context['object_list'].question.all():
print(question.foo)
但是print(question.foo)
给了我这个错误:
Traceback (most recent call last):
File "/home/user1/env/gemafication/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user1/env/gemafication/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/user1/env/gemafication/local/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/user1/env/gemafication/local/lib/python2.7/site-packages/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/home/user1/env/gemafication/local/lib/python2.7/site-packages/django/views/generic/list.py", line 152, in get
context = self.get_context_data()
File "/home/user1/projects/db_autotest/app/knowledge_test/views.py", line 88, in get_context_data
print(question.foo)
AttributeError: 'Question' object has no attribute 'foo'
我做错了什么?
答案 0 :(得分:0)
每次迭代都是从数据库中获取的新查询集,因此第二次迭代不具有您在第一次迭代中设置的属性。
您可以在第一个循环之前转换为列表,然后迭代该列表而不是新的查询集。