问题
I need to create my own intermediate model.
class class1(models.Model)
class class2(models.Model):
field1 = models.ManyToManyField(class1, through="class3")
class class3(models.Model):
field1 = models.ForeignKey(class1)
field2 = models.ForeignKey(class2)
field3 = models.IntegerField()
class Meta:
auto_created = True
I use "auto_created=True" because in the following code, I had the error :
AttributeError: Cannot use add() on a ManyToManyField which specifies an intermediary model.
for m2m_field in self._meta.many_to_many:
for m2m_link in getattr(self, m2m_field.get_attname()).all():
getattr(to_object, m2m_field.get_attname()).add(m2m_link)
Now it works fine, but when I try to do a makemigration, django wants to remove my class3 (the intermediate class), and removing the "through" attribute in the field1 in class2.
What am I doing wrong ? Any solutions ?
Tks all.
回答1:
As far as I am aware, the auto_created
attribute in the Meta
class is undocumented, so you should avoid using it.
As the AttributeError
says, it is not possible to use add()
for a many to many field that uses an intermediary model. The correct fix is to create an instance of the intermediate model, instead of using add()
.
class3.objects.create(field_1=c1, field_2=c2, field_3=1).
See the docs on extra fields in many to many relationships for more info.
来源:https://stackoverflow.com/questions/34394323/how-to-correctly-use-auto-created-attribute-in-django