python - ManyToManyField 通过抽象模型

标签 python django many-to-many abstract django-orm

这里有一个有趣的..我已经缩短了模型以使其更容易理解..

class Participant(Person):
    passport_number = models.IntegerField(verbose_name=_('Passport Number'), db_column=u'PassportNumber')

    class Meta:
        db_table = u'Participant'

class Journey(BaseModel):
    participants = models.ManyToManyField(Participant, related_name='%(app_label)s_%(class)s_participants', through=u'ParticipantJourney')

    class Meta:
        abstract = True

class PlaneJourney(Journey):
    flight_number = models.CharField(max_length=16, verbose_name=_('Flight Number'), db_column=u'FlightNumber')

    class Meta:
        db_table = u'PlaneJourney'

class ParticipantJourney(BaseModel):
    participant = models.ForeignKey(Participant, verbose_name=_('Participant'), db_column=u'ParticipantId')

    journey_content_type = models.ForeignKey(ContentType, related_name='journey_content_type')
    journey_object_id = models.PositiveIntegerField()
    journey = generic.GenericForeignKey('journey_content_type', 'journey_object_id') # models.ForeignKey(Journey, verbose_name=_('Journey'), db_column=u'JourneyId')

    payment_content_type = models.ForeignKey(ContentType, related_name='payment_content_type')
    payment_object_id = models.PositiveIntegerField()
    payment = generic.GenericForeignKey('payment_content_type', 'payment_object_id') # models.ForeignKey(Payment, verbose_name=_('Payment'), db_column=u'PaymentId')

    class Meta:
        db_table = u'ParticipantJourney'

ParticipantJourney 模型将参与者与旅程联系起来,现在旅程是抽象的,因为它可以通过任意数量的不同交通方式进行,每种交通方式都有自己各自的领域。我认为此设置是正确的,但我收到以下错误消息:

Error: One or more models did not validate: kandersteg.planejourney: 'participants' is a manually-defined m2m relation through model ParticipantJourney, which does not have foreign keys to Participant and PlaneJourney

我需要保留链接表的手动定义,这样我也可以将付款链接到所述旅程,所以我真的不知道下一步该去哪里,如果有人能阐明一些信息,我会非常感激!

干杯, 亚历克斯

最佳答案

Django 不将通用外键视为 through 模型中必需的外键,目前无法在抽象基类中定义与 through 的 ManyToMany 关系。

但是,django 中有一个功能请求(ticket #11760),它使您还可以在 through 字段中使用 %(class)s,例如通过在 Journey 模型中使用 through='Pariticipant_%(class)s',然后您必须为 Journey 的每个 child 手动创建 throught 表>。但正如我所说,它只是一个开放的功能请求。

关于python - ManyToManyField 通过抽象模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8952542/

相关文章:

java - 多对多 Spring Jpa 删除不起作用

python - Plotly 热图中颜色条的标题

Python:通过 iter() 在 ElementTree 中使用命名空间

Django Tastypie 通过 PostMan REST 客户端与 API 交互

python - Apache 子进程在分配一个巨大的 block 后不释放内存

c# - 级联还是不级联? ("object references an unsaved transient instance"错误)

python - 使用 python 和 .pem 文件通过 SCP 进行文件传输的最佳方法

python - 从私有(private) pypiserver 安装 python 包

django - 如何在 Flex 中读取 Django HTTPResponse?

python - 多对多查询 (Django)