문제

I want to add attributes in objects, which included m2m filed.

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)

but print(question.foo) gives me this error:

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'

What am I doing wrong?

도움이 되었습니까?

해결책

Each iteration is a new queryset fetched from the database, so the second iteration doesn't have the attributes you set on the first one.

You could convert to a list before the first loop, then subsequently iterate over that list rather than the new queryset.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top