Django:当数据库发生变化时异步执行某些功能的最简单方法是什么?
Django: What is the simplest way to asynchronously execute some function when there is a change to the database?
我熟悉 Oracle 中的 DBMS_ALERT 功能,当数据库发生变化时,它会向操作系统发送警报,并且对一般的数据库触发器比较熟悉。我浏览了有关信号的 django 文档,如果没有更简单的方法,我倾向于使用它们。
只要数据库中有更新或创建的记录,我想做的就是在系统文件系统上更新或创建外部文件。我希望在 models.py 中调用和定义此方法,如下所示。
models.py
from django.db import models
from django.shortcuts import reverse
class Entry(models.Model):
subject = CharField(max_length=20, unique=True)
content = models.TextField(blank=False)
class Meta:
ordering = ['subject']
def __str__(self):
"""String for representing the Model object."""
return self.subject
def get_absolute_url(self):
"""Returns the url to access a detail record for this entry."""
return reverse('entry_detail', args=[int(self.id)])
def ondbchange_updatecorrfile(self):
# this method would be called upon change in the model Entry, so it is already aware of object
util.save_entry(self.subject,self.content) # file corresponding to row is updated or created
实现上面的 ondbchange_updatecorrfile(self) 方法最简单的方法是什么?
我查看了来自 this source
的以下代码
models.py
class Entry(models.Model):
...
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Entry)
def queue_task(sender, instance, created, **kwargs):
tasks.foo.delay(object=instance)
然后 foo 是另一个 class 中的某个函数,它会更新文件。由于数据库模型是class,它知道模型底层数据库的变化,如果所需的函数已经在模型中并且“自我意识到”数据库变化,我们真的需要使用信号吗?
非常感谢任何帮助。请具体一点,细节决定成败。
post_save信号是模型Entry在保存后发送的,但是根据,该信号不包括其update_fields参数中的模型变化。这些必须手动插入到发生 save() 的函数的重写中;这违背了目的。我最初假设信号会自动包含此信息。
我熟悉 Oracle 中的 DBMS_ALERT 功能,当数据库发生变化时,它会向操作系统发送警报,并且对一般的数据库触发器比较熟悉。我浏览了有关信号的 django 文档,如果没有更简单的方法,我倾向于使用它们。
只要数据库中有更新或创建的记录,我想做的就是在系统文件系统上更新或创建外部文件。我希望在 models.py 中调用和定义此方法,如下所示。
models.py
from django.db import models
from django.shortcuts import reverse
class Entry(models.Model):
subject = CharField(max_length=20, unique=True)
content = models.TextField(blank=False)
class Meta:
ordering = ['subject']
def __str__(self):
"""String for representing the Model object."""
return self.subject
def get_absolute_url(self):
"""Returns the url to access a detail record for this entry."""
return reverse('entry_detail', args=[int(self.id)])
def ondbchange_updatecorrfile(self):
# this method would be called upon change in the model Entry, so it is already aware of object
util.save_entry(self.subject,self.content) # file corresponding to row is updated or created
实现上面的 ondbchange_updatecorrfile(self) 方法最简单的方法是什么?
我查看了来自 this source
的以下代码models.py
class Entry(models.Model):
...
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Entry)
def queue_task(sender, instance, created, **kwargs):
tasks.foo.delay(object=instance)
然后 foo 是另一个 class 中的某个函数,它会更新文件。由于数据库模型是class,它知道模型底层数据库的变化,如果所需的函数已经在模型中并且“自我意识到”数据库变化,我们真的需要使用信号吗?
非常感谢任何帮助。请具体一点,细节决定成败。
post_save信号是模型Entry在保存后发送的,但是根据