나는 장고에 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()
이라고 부르면 my_model.m2m_field
에 RelatedManager
개체가 생기고 my_model.m2m_field.add(other_model_instance)
으로 전화 할 수 있습니다.
하지만 .... 사전에이 작업을 수행 할 수있는 방법이 있습니까? 때때로 특정 분야가없는 무언가를 올리는 것은 그리 좋지 않습니다.
"사전에 처리 하시겠습니까?" 많은 필드를 추가하기 전에 항상 모델을 저장해야합니다. – jproffitt
다른 모델 아래에 mymodel을 두거나 참조 주변에 따옴표를 추가하십시오. – karthikr