我试图通过多表继承来扩展库模型,而这就是我最终得到的结果:

class CompetitionMedia(InstagramMedia):
    visible = models.BooleanField(default=True)
    most_creative = models.BooleanField(default=False)

@receiver(post_save, sender=InstagramMedia, dispatch_uid='create_competition_media')
def create_competition_media(sender, instance, created, **kwargs):
    competition_media = CompetitionMedia()
    competition_media.instagrammedia = instance
    competition_media.save() # fails

@receiver(post_save, sender=InstagramMedia, dispatch_uid='create_competition_media2')
def create_competition_media2(sender, instance, created, **kwargs):
    CompetitionMedia.objects.create(instagrammedia=instance) # Fails


是否有可能做到这一点?

最佳答案

据我了解,您想要得到这样的东西:

class CompetitionMedia(models.Model):
    instagrammedia = models.OneToOneField(InstagramMedia, primary_key=True)
    visible = models.BooleanField(default=True)
    most_creative = models.BooleanField(default=False)

@receiver(post_save, sender=InstagramMedia, dispatch_uid='create_competition_media2')
def create_competition_media(sender, instance, created, **kwargs):
    if created:
         CompetitionMedia.objects.create(instagrammedia=instance)

关于python - 在Django中使用多表继承时,是否可以直接设置隐式OneToOne键?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12345959/

10-12 19:51