python - 如何将 post_save 接收器与 django-polymorphic 一起使用?

标签 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')

最佳答案

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

我最终做的是@receiver注释中声明sender。这会导致回调由每个 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 .

关于python - 如何将 post_save 接收器与 django-polymorphic 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426309/

相关文章:

函数返回类型中的 F# 多态性

python - 如何将字符串句子作为命令行参数传递

python - 如何处理一个 pandas 数据帧的行中的 ID 组并使用它们从另一个数据帧中提取记录

django - 在 django 开发期间提供用户上传的文件

python - 如何查看在 Django 的 manage.py test 命令期间运行了哪些测试

c++ - 继承类在这种情况下如何工作???

c++ - 编译器如何确定它正在寻址哪种多态类型

python - 尝试在输出中返回多个值

python - 在Python中将不同的数据类型从XML加载到字典中

django - React + Django 的最佳安全实践