【问题标题】:django model inheritance & FK, could not create unique indexdjango 模型继承和 FK,无法创建唯一索引
【发布时间】:2016-01-17 00:20:36
【问题描述】:

我希望能够拥有一个父类的外键,从而也允许查询子类。所有其他解决方案都是噩梦。 我试图做到这一点(Destination 也是一个父类,它有 # 个我想要关联的子类):

class Destination(PolymorphicModel)

class Account(Destination)

class Organization(Destination)

class Person(Destination)

class Transaction(models.Model)
    destination = models.ForeignKey(Destination, verbose_name="Destination", null=True, blank=True,
                                related_name="CompletedTransaction_Destination_FK")

我也在其他地方引用目的地。 这是我尝试迁移时收到的错误消息:

psycopg2.IntegrityError:无法创建唯一索引“baseapp_organization_organization_destination_ptr_id_key” 详细信息:键 (organization_destination_ptr_id)=(1) 重复。

如果我能做目标课程,我会很高兴的

abstract = True

但是我不能有外键。我需要能够选择所有这些目的地,并且它们需要在数据库中保持独特的真实模型。

我也尝试过 GenericRelations,但正如我之前所说,这被证明是一场噩梦。

感觉我可以通过某种方式绕过这个错误,有什么帮助吗?

【问题讨论】:

    标签: django inheritance foreign-keys polymorphism unique-index


    【解决方案1】:

    解决方案,我猜它适用于无法创建索引的其他错误,是擦除数据库并删除所有迁移。确实很痛苦,但现在我可以做到:

    destinations = Destination.objects.all()
    

    它会给我所有的对象,根据django polymorphic

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-11
      • 2018-09-24
      • 1970-01-01
      • 2021-06-22
      • 2019-12-04
      • 2011-03-10
      • 1970-01-01
      • 2021-10-30
      相关资源
      最近更新 更多