加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – ManyToManyField与抽象模型

发布时间:2020-12-20 13:26:05 所属栏目:Python 来源:网络整理
导读:这里有一个有趣的…我缩短了模型,使其更容易理解.. class Participant(Person): passport_number = models.IntegerField(verbose_name=_('Passport Number'),db_column=u'PassportNumber') class Meta: db_table = u'Participant'class Journey(BaseModel):
这里有一个有趣的…我缩短了模型,使其更容易理解..

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表.但正如我所说,它只是一个开放的功能请求.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读