Django信号,在保存列表器上实现 [英] Django signals, implementing on save listner

查看:34
本文介绍了Django信号,在保存列表器上实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解信号的工作方式时遇到困难,我浏览了一些页面,但没有一个页面帮助我获得图像.

我有两个模型,我想创建一个信号,当记录保存在父模型中时,该信号将保存在子模型中.实际上,我希望孩子在我的应用程序中侦听任何父母,因为这个孩子尤其是通用外键.

core/models.py

django.db导入模型中的

 从django.contrib.auth.models导入用户从django.contrib.contenttypes.models导入ContentType从django.contrib.contenttypes导入通用类Audit(models.Model):## TODO:文档#通过DJANGO内容类型使用通用关系的多态模型操作= models.CharField(max_length = 40)operation_at = models.DateTimeField("Operation At",auto_now_add = True)operation_by = models.ForeignKey(User,db_column ="operation_by",related_name =%(app_label)s _%(class)s_y +")content_type = models.ForeignKey(ContentType)object_id = models.PositiveIntegerField()content_object =通用.GenericForeignKey('content_type','object_id') 

workflow/models.py

django.db导入模型中的

 从django.contrib.auth.models导入用户从django.contrib.contenttypes.models导入ContentType从django.contrib.contenttypes导入通用从core.models导入审核类Instances(models.Model):## TODO:文档## TODO:将ID替换为XXXX-XXXX-XXXX-XXXX# 关于INSTANCE_STATUS =((我",进行中"),("C",已取消"),("D",已删除"),("P",待处理"),("O",已完成"))id = models.CharField(max_length = 200,primary_key = True)status = models.CharField(max_length = 1,choices = INSTANCE_STATUS,db_index = True)audit_obj = generic.GenericRelation(审核,editable = False,null = True,空白= True)def save(self,* args,** kwargs):#在新记录上生成一个新的uuid如果self.id为None或self.id .__ len __()为0:导入uuidself.id = uuid.uuid4().__ str __()超级(实例,自我).save(* args,** kwargs)类Setup(models.Model):## TODO:文档#通过DJANGO内容类型使用通用关系的多态模型content_type = models.ForeignKey(ContentType)object_id = models.PositiveIntegerField()content_object = generic.GenericForeignKey('content_type','object_id')Actions(models.Model)类:ACTION_TYPE_CHOICES =(("P","Python脚本"),("C",类名"),)名称= models.CharField(max_length = 100)action_type = models.CharField(max_length = 1,choices = ACTION_TYPE_CHOICES)类Tasks(models.Model):名称= models.CharField(max_length = 100)Instance = models.ForeignKey(实例) 

我正在努力在Audit模型中创建一个侦听器,以便我可以将其与Instance模型连接起来.如果在Instance中插入了一条新记录,它也会自动在Audit中插入一个记录.然后,计划将该监听器连接到我的应用中的多个模型,

你知道我该怎么做吗?

解决方案

使用以下代码,您可以使用after_save_instance_handler方法连接实例对象的保存.在这种方法中,您将创建与审核的关系.另请参见通用关系文档

我通常将信号添加到定义了发送方的models.py中.不知道是否需要这样做.

来自django.db.models.signals的

 导入post_save##### SIGNALS ######def after_save_instance_handler(sender,** kwargs):#获取保存的实例instance_object = kwargs ['instance']#获取所需的数据the_date = ...the_user = ...the_object_id = ...#创建与审核对象的关系instance_object.audit_obj.create(operation ="op963",operation_at = the_date,operation_by = the_user,object_id = the_object_id)#使用后保存信号连接处理程序-Django 1.1 + 1.2post_save.connect(after_save_instance_handler,sender = Instances) 

django 1.2信号

在Django开发版本中,他们添加了一个装饰器来连接信号.因此,除了上面的调用,您必须将此装饰器添加到处理程序中

  @receiver(post_save,sender = Instances)def after_save_instance_handler(sender,** kwargs): 

django开发信号

am having difficulties understanding how signals works, I went through some pages but none of them helped me get the picture.

I have two models, I would like to create a signal that will save in the child model when a record is saved in the parent. Actually, I want the child to be listening across my application for any parent since this child in particular of a generic foreign key.

core/models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(max_length=40)
    operation_at = models.DateTimeField("Operation At", auto_now_add=True)
    operation_by = models.ForeignKey(User, db_column="operation_by", related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

workflow/models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from core.models import Audit


class Instances(models.Model):
    ##  TODO: Document
    ##  TODO: Replace id with XXXX-XXXX-XXXX-XXXX
    # Re
    INSTANCE_STATUS = (
        ('I', 'In Progress' ),
        ('C', 'Cancelled'   ),
        ('D', 'Deleted'     ),
        ('P', 'Pending'     ),
        ('O', 'Completed'   )
    )

    id=models.CharField(max_length=200, primary_key=True)
    status=models.CharField(max_length=1, choices=INSTANCE_STATUS, db_index=True)
    audit_obj=generic.GenericRelation(Audit, editable=False, null=True, blank=True)


    def save(self, *args, **kwargs):
        # on new records generate a new uuid
        if self.id is None or self.id.__len__() is 0:
            import uuid
            self.id=uuid.uuid4().__str__()
        super(Instances, self).save(*args, **kwargs)



class Setup(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    content_type=models.ForeignKey(ContentType)
    object_id=models.PositiveIntegerField()
    content_object=generic.GenericForeignKey('content_type', 'object_id')


class Actions(models.Model):
    ACTION_TYPE_CHOICES = (
        ('P', 'Python Script'),
        ('C', 'Class name'),
    )
    name=models.CharField(max_length=100)
    action_type=models.CharField(max_length=1, choices=ACTION_TYPE_CHOICES)


class Tasks(models.Model):
    name=models.CharField(max_length=100)
    Instance=models.ForeignKey(Instances)

Am struggling to create a listener in Audit model so I can connect it with Instance model, If a new record inserted in Instance it will automatically inserts one in Audit as well. Then, am planning to connect this listener to several models in my app,

Any idea how I can do such a thing?

解决方案

With the code below you can connect the save of an Instance object, with the after_save_instance_handler method. In this method you create the relation to the Audit. Please also see the generic relations doc

I usually add the signals in the models.py where the sender has been defined. Not sure if this is needed.

from django.db.models.signals import post_save

#####SIGNALS######
def after_save_instance_handler(sender, **kwargs):
    #get the saved instance
    instance_object = kwargs['instance']

    #get the needed data
    the_date = ...
    the_user = ...
    the_object_id = ...

    #create the relation to the audit object
    instance_object.audit_obj.create(operation="op963",operation_at=the_date,operation_by=the_user,object_id=the_object_id)

#connect the handler with the post save signal - django 1.1 + 1.2
post_save.connect(after_save_instance_handler, sender=Instances)

django 1.2 signals

in django development version they added a decorator to connect the signal. thus instead of the call above you have to add this decorator to the handler

@receiver(post_save, sender=Instances)
def after_save_instance_handler(sender, **kwargs):

django dev signals

这篇关于Django信号,在保存列表器上实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆