django related_name不起作用

时间:2015-09-16 14:37:21

标签: django django-models django-forms

我有复杂的模型:

class Person(models.Model):
  names = models.ManyToManyField('Name')
  wives = models.ManyToManyField('Person',related_name='husbands',null = True, blank = True)

表格:

class PersonForm(ModelForm):
  names_list = forms.ModelMultipleChoiceField(queryset=Person.objects.filter(names_set__id=2), widget=forms.CheckboxSelectMultiple(attrs={"checked":""}))
  wives_list = forms.ModelMultipleChoiceField(queryset=Person.objects.filter(husbands__id=2), widget=forms.CheckboxSelectMultiple(attrs={"checked":""}))

     class Meta:
        model = Person
        fields = ('names','wives')
        widgets = {
         'names' : forms.HiddenInput(),
         'wives': forms.HiddenInput(),
        }

不幸的是 - 由于未知的原因 - 妻子的作品,名字 - 不要 - 不要。我试图添加related_name:

names = models.ManyToManyField('Name', related_name='name_owners')

But not. The Error is: 
FieldError at /mysite/edit/2/
Cannot resolve keyword 'name_owners' into field. Choices are: husbands, id, names, wives

我重构代码(早期名称只是一个文本)我忘了改变什么?

Trackback:
Environment:


Request Method: GET
Request URL: 

Django Version: 1.7.7
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.admindocs',
 'django.contrib.staticfiles',

)
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  98.                 resolver_match = resolver.resolve(request.path_info)
File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
  345.                     sub_match = pattern.resolve(new_path)
File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
  345.                     sub_match = pattern.resolve(new_path)
File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
  224.             return ResolverMatch(self.callback, args, kwargs, self.name)
File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in callback
  231.         self._callback = get_callable(self._callback_str)
File "/usr/lib/python2.7/dist-packages/django/utils/lru_cache.py" in wrapper
  101.                     result = user_function(*args, **kwds)
File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in get_callable
  97.             mod = import_module(mod_name)
File "/usr/lib/python2.7/importlib/__init__.py" in import_module
  37.     __import__(name)
File "/home/excursor/frontoffice/views.py" in <module>
  35. class DiggerForm(ModelForm):
File "/home/excursor/frontoffice/views.py" in DiggerForm
  139.   names_list = forms.ModelMultipleChoiceField(,queryset=Person.objects.filter(names_set__id=2), widget=forms.CheckboxSelectMultiple(attrs={"checked":""}))
File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method
  92.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py" in filter
  691.         return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py" in _filter_or_exclude
  709.             clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_q
  1331.         clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in _add_q
  1358.                     current_negated=current_negated, connector=connector)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in build_filter
  1182.         lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in solve_lookup_type
  1120.         _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in names_to_path
  1427.             self.raise_field_error(opts, name)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in raise_field_error
  1433.                          "Choices are: %s" % (name, ", ".join(available)))

Exception Type: FieldError at 
Exception Value: Cannot resolve keyword 'names_set' into field. Choices are:  husbands, id, names, wives

1 个答案:

答案 0 :(得分:1)

您误解了related_name的工作原理。

Person.objects.filter()将永远归还给人,而不是名字。

如果您需要名称的查询集,请执行

Name.objects.filter(person=2)

这将返回与ID为2的人关联的姓名(您不需要__id,因为ID是主键。

您的代码适用于丈夫/妻子的原因是该字段链接到同一模型。