编程语言
首页 > 编程语言> > python – ManyToManyField与抽象模型

python – ManyToManyField与抽象模型

作者:互联网

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

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定义ManyToMany关系.

但是,django(ticket #11760)中有一个功能请求,它允许您在通过字段中使用%(类),例如通过在Journey模型中使用through =’Pariticipant _%(class)s’,然后您必须为Journey的每个孩子手动创建viat表.但正如我所说,它只是一个开放的功能请求.

标签:python,abstract,django,many-to-many,django-orm
来源: https://codeday.me/bug/20190709/1416874.html