如何使用django-polymorphic的post_save接收器?

时间:2016-07-17 21:57:10

标签: python django polymorphism

我有一个django-polymorphic模型,想要实现一个post_save信号来自动创建一个多态的相关模型。

它类似于下面的代码,相关的非工作代码是@receiver装饰work_post_save方法。问题是实例是ctype_id而不是对象。

from django.db import models
from django.db.models import signals
from django.dispatch import receiver
from polymorphic.models import PolymorphicModel

from mygallery.models import Album

# Work Parent PolymorphicModel
class Work(PolymorphicModel):
    title = models.CharField(blank=True,max_length=256)
    slug = models.SlugField(max_length=256)

@receiver(signals.post_save, sender=Work)
def work_post_save(sender, instance, signal, created, **kwargs):
    album, new = Album.objects.get_or_create(title=instance.title + ' Stills', slug=instance.slug + '-stills')
    work_album, new = WorkAlbum.objects.get_or_create(work=instance, album=album, is_key=True)


class ArtProject(Work):
    manifesto = models.CharField(blank=True,max_length=256)

class CodeProject(Work):
    code = models.CharField(blank=True,max_length=256)


# Content Parent PolymorphicModel
class WorkContent(PolymorphicModel):
    is_key = models.BooleanField(default=False, unique=True, default=False)


class WorkAlbum(WorkContent):
    work = models.ForeignKey(Work, related_name='work_albums')
    album = models.ForeignKey(Album, related_name='album_works')

1 个答案:

答案 0 :(得分:0)

我只是稍微摆弄了这一点,所以我不能100%确定处理这个问题的正确方法是什么。

我最终做的是sender注释中声明@receiver。这具有每个post_save信号触发回调的效果。然后在回调中,我使用我的父模型(在您的情况下为isinstance())检查Work,以便仅在我感兴趣的模型被保存之后执行回调。执行回调时,instance参数是子模型(在您的情况下为ArtProjectCodeProject)。

@receiver(signals.post_save)
def work_post_save(sender, instance, signal, created, **kwargs):
    if isinstance(instance, Work):
        # instance is either ArtProject or CodeProject
        album, new = Album.objects.get_or_create(title=instance.title + ' Stills', slug=instance.slug + '-stills')
        work_album, new = WorkAlbum.objects.get_or_create(work=instance, album=album, is_key=True)

直接在父save()上触发显然是not supported