1

我正在尝试通过多表继承来扩展库模型,这就是我最终得到的:

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

是否有可能做到这一点?

4

2 回答 2

1

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

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)
于 2012-09-10T12:51:29.347 回答
0

我显然应该设置parent_ptr,例如:

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

但是,如果您先创建并保存父级然后尝试创建子级,则存在一个问题,即使在您尚未在子级中设置的字段上,子级也会覆盖父级。如https://code.djangoproject.com/ticket/11618https://code.djangoproject.com/ticket/7623中所述,所以我会避免它,因为它不是很明显会发生。

如果有人真的想走那条路,你需要做:

@receiver(post_save, sender=InstagramMedia, dispatch_uid='create_competition_media')
def create_competition_media2(sender, instance, created, **kwargs):
    if created:
        CompetitionMedia.objects.create(instagrammedia_ptr=instance)
        instance.save() # This should re-save the parent values.

更好的是:

@receiver(post_save, sender=InstagramMedia, dispatch_uid='create_competition_media')
def create_competition_media2(sender, instance, created, **kwargs):
    if created:
        CompetitionMedia.objects.create(instagrammedia_ptr=instance,
            **instance.__dict__)
于 2012-09-10T17:10:25.413 回答