在Django中,如果孩子被保存在外键关系中,该怎么通知父母? [英] In Django how do I notify a parent when a child is saved in a foreign key relationship?

查看:91
本文介绍了在Django中,如果孩子被保存在外键关系中,该怎么通知父母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种模式:

class Activity(models.Model):
    name = models.CharField(max_length=50, help_text='Some help.')
    entity = models.ForeignKey(CancellationEntity)
    ...


class Cancellation(models.Model):
    activity = models.ForeignKey(Activity)
    date = models.DateField(default=datetime.now().date())
    description = models.CharField(max_length=250)
    ...

我希望活动模型在取消相关

I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).

最好的方法是什么?

推荐答案

你想查看的是 Django的信号(也请参阅此页面),具体来说,模型信号 - - 更具体地说, post_save 信号。信号是Django的插件/挂钩系统版本。 post_save信号在每次保存模型时发送,无论是更新还是创建(并且它会让您知道是否已创建)。这是您如何使用信号在活动取消时获得通知

What you want to look into is Django's signals (check out this page too), specifically the model signals--more specifically, the post_save signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation

from django.db.models.signals import post_save

class Activity(models.Model):
    name = models.CharField(max_length=50, help_text='Some help.')
    entity = models.ForeignKey(CancellationEntity)

    @classmethod
    def cancellation_occurred (sender, instance, created, raw):
        # grab the current instance of Activity
        self = instance.activity_set.all()[0]
        # do something
    ...


class Cancellation(models.Model):
    activity = models.ForeignKey(Activity)
    date = models.DateField(default=datetime.now().date())
    description = models.CharField(max_length=250)
    ...

post_save.connect(Activity.cancellation_occurred, sender=Cancellation)

这篇关于在Django中,如果孩子被保存在外键关系中,该怎么通知父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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