如何在 Django 中正确使用 auto_created 属性?

How to correctly use auto_created attribute in django?

我需要创建自己的中间模型。

class class1(models.Model):
    pass

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

我使用 auto_created=True 因为在下面的代码中,我有错误:

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)

现在它工作正常,但是当我尝试做一个 makemigration 时,django 想要删除我的 class3(中间 class),并删除 through class2 中的 field1 中的属性。

我做错了什么?任何解决方案?

谢谢大家。

据我所知,Meta class 中的 auto_created 属性未记录,因此您应该避免使用它。

正如AttributeError所说,对于使用中介模型的多对多字段,不可能使用add()。正确的解决方法是创建中间模型的实例,而不是使用 add().

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

有关详细信息,请参阅 extra fields in many to many relationships 上的文档。