【问题标题】:How to correctly use auto_created attribute in django?如何在 django 中正确使用 auto_created 属性?
【发布时间】:2016-03-27 10:44:15
【问题描述】:

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

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(中间类),并删除 class2field1 中的 through 属性。

我做错了什么?有什么解决办法吗?

谢谢。

【问题讨论】:

  • 我有完全相同的问题,这是我的解决方案(参考:stackoverflow.com/questions/28693691/…)你可以运行“makemigrations”来获取自动生成的脚本,然后覆盖那里的应用和取消应用方法,这样当你运行“迁移”命令,这些操作将不会运行。
  • 在某些情况下,您可以使用this trick 来获得auto_created 行为,而不会影响您的迁移。

标签: python django django-models many-to-many


【解决方案1】:

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

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

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

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

【讨论】:

  • 是的,我在 django 文档中没有发现任何关于 auto_created 属性的信息。谢谢。
  • 但是,你知道django为什么要删除我的中间类吗?
  • 我不熟悉auto_created,所以我不知道为什么它会导致Django想要删除你的中间类。我假设如果你停止使用它,那么 Django 就不想再删除中间类了。
  • @Raphael 在迁移中,auto_created 模型由 AddField 操作为 ManyToManyField 创建——它不作为单独的模型存在,仅作为模型的一部分存在定义 m2m 字段。因为迁移生成器不再看到模型注册表中的模型,所以它会尝试删除它。您(还)不能从具有显式模型的 m2m 更改为自动创建的模型,或者相反。
猜你喜欢
  • 1970-01-01
  • 2018-10-21
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多