Skip to main content
 首页 » 编程设计

python之Django 在数据库值更改时发送推送通知

2024年08月21日34qq号

我是 Django 的新手,我必须创建一个服务器,该服务器能够检测数据库中的特定值何时小于 X,然后向特定用户发送通知。

我的想法是这样的:

  1. 检测到小于 X 的值。
  2. 服务器向数据库中的通知表添加一条通知记录。
  3. 服务器向指定用户发送推送通知。

在应用程序中有一个读取上述表格的通知 View 。

我能够实现第 2 点和第 3 点,但我不知道如何开始第 1 点。

请您参考如下方法:

可以通过覆盖保存方法或使用 post_save 信号来实现。

第一个选项可能是这样的:

class Foo(model.Model): 
    # here you define your fields 
    def save(self, *args, **kwargs): 
        super(Foo, self).save(*args, **kwargs) 
        if self.desired_field < X: 
            # logic goes here 

第二个选项可以这样实现:

class Foo(model.Model): 
    # here you define your fields 
 
@receiver(post_save, sender=Foo) 
def notify(sender, instance, **kwargs): 
    if instance.desired_field < X: 
       # logic goes here