0
這就是我想要做的事:如何在運行時添加ManyToManyField?
def test_basic_addition(self):
# create field
f = models.ManyToManyField(to=X, related_name='bar')
f.contribute_to_class(Y, 'x')
# create table
field = Y._meta.get_field_by_name('x')[0]
through = field.rel.through
fields = tuple((field.name, field) for field in through._meta.fields)
db.create_table(through._meta.db_table, fields)
db.create_unique(through._meta.db_table,
['%s_id' % name for name, f in fields
if isinstance(f, models.ForeignKey)])
x = X(name='foo')
x.save()
y = Y()
y.save()
y.x.add(x)
print y.x.all()
引發的異常是:
E
======================================================================
ERROR: test_basic_addition (test_app.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/jpic/test_project/test_app/tests.py", line 41, in test_basic_addition
print y.x.all()
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 116, in all
return self.get_query_set()
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 543, in get_query_set
return super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters)
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 621, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 639, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1122, in add_filter
process_extras=process_extras)
File "/home/jpic/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1316, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'bar' into field. Choices are: id, name, users
----------------------------------------------------------------------
Ran 1 test in 0.017s
FAILED (errors=1)
Destroying test database for alias 'default'...
del X._meta._name_map
不會做的伎倆,但我想這是正常的,因爲它是一個反向字段來從另一個型號,Y.
無論如何,您可以結帳我的test_project它隔離我的問題,然後在您的工作副本中運行./manage.py test test_app
重現此問題。