How to use auto_created attribute in django correctly?

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 an error:

AttributeError: Cannot use add () on ManyToManyField, which points to an intermediate 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 makemigration, django wants to remove my class3 (intermediate class) and remove the β€œthrough” attribute in field1 in class2.

What am I doing wrong? Any solutions?

Tks all.

+6
source share
1 answer

To my knowledge, the auto_created attribute in the Meta class is undocumented, so you should avoid using it.

As AttributeError says, it is not possible to use add() for many fields using an intermediate model. The correct fix is ​​to instantiate the intermediate model instead of using add() .

 class3.objects.create(field_1=c1, field_2=c2, field_3=1). 

For more information, see the docfields docs in many ways .

+8
source

All Articles