这里有一个有趣的..我已经缩短了模型以使其更容易理解..
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/