0
假設我在Django中有一個manytomany字段的模型。添加到ManyToMany提前
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)
。
但....有什麼辦法提前做到這一點?有時候發佈某些沒有特定領域的東西並不是很好。
你是什麼意思「提前做這個」?在添加許多字段之前,您總是必須保存模型。 – jproffitt
要麼將mymodel放在othermodel的下面,要麼在引用周圍加引號 – karthikr