假设我在 Django 中有一个具有多态字段的模型。
class MyModel(models.Model):
m2m_field = models.ManyToMany(OtherModel)
class OtherModel(models.Model):
some_text = models.CharField(max_length=256)
如果我列出 MyModel 的属性,则在我保存之前没有 m2m_field。
>>> my_model.m2m_field
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py", line 897, in __get__
through=self.field.rel.through,
File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py", line 586, in __init__
(instance, source_field_name))
ValueError: "<MyModel>" needs to have a value for field "mymodel" before this many-to-many relationship can be used.
好吧,够公平的。所以我打电话my_model.save()
,然后我得到一个RelatedManager
对象my_model.m2m_field
,我可以打电话my_model.m2m_field.add(other_model_instance)
。
但是....有什么办法可以提前做到这一点?有时在没有特定字段的情况下发布内容并不是很好。