如何订阅Django数据库的更新

huangapple go评论60阅读模式
英文:

How to Subcribe to an update of database django

问题

当使用Django模型时,我有一个表格名为"AppConfig"。

我想要的是,每当在AppConfig表格上进行更新(包括创建、修改、删除),结果将记录到一个文件中。

是否有一种方便的方法来实现这个?

我可以通过在代码中每次更新Config表格时都添加日志函数来实现这一点。但这样做会很混乱,而且存在错误的可能性。

英文:

When using Django model, I have an table name "AppConfig".

What I want is that whenever there is an update on AppConfig table (inluding create,modify,delete) the result will log into a file.

Is there an convenient way to do it.

I can do this by adding log function to every point that I update the Config table in code. But it is quite messy and there is potential of mistake.

答案1

得分: 1

是的,如上面的评论所说,您可以使用信号。

试试这个,

在您的应用程序目录中创建一个名为signals.py的文件。

# signals.py
from django.db.models.signals import post_save, post_delete, pre_delete
from django.dispatch import receiver
from .models import AppConfig

@receiver(post_save, sender=AppConfig)
def log_appconfig_update(sender, instance, created, **kwargs):
    if created:
        action = "created"
    else:
        action = "modified"

    print(f"AppConfig {action}: {instance}")
    # 在这里编写您的逻辑

@receiver([post_delete, pre_delete], sender=AppConfig)
def log_appconfig_delete(sender, instance, **kwargs):
    print(f"AppConfig deleted: {instance}")

然后在您的apps.py中注册这些信号。

from django.apps import AppConfig # 不要与models.AppConfig混淆

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'your_app_name'

    def ready(self):
        import your_app_name.signals

有了这个设置,每次创建、修改或删除一个AppConfig实例时,将在终端上打印相应的消息。

英文:

Yes as said in the above comment you can make use of signals.

Give this a try,

Create a signals.py file in your app directory.

# signals.py
from django.db.models.signals import post_save, post_delete, pre_delete
from django.dispatch import receiver
from .models import AppConfig

@receiver(post_save, sender=AppConfig)
def log_appconfig_update(sender, instance, created, **kwargs):
    if created:
        action = "created"
    else:
        action = "modified"

    print(f"AppConfig {action}: {instance}")
    # Write Your Logic Here

@receiver([post_delete, pre_delete], sender=AppConfig)
def log_appconfig_delete(sender, instance, **kwargs):
    print(f"AppConfig deleted: {instance}")

then register the signals in your apps.py

from django.apps import AppConfig # don't confuse with models.AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'your_app_name'

    def ready(self):
        import your_app_name.signals

With this setup, every time an AppConfig instance is created, modified, or deleted, the corresponding message will be printed to terminal.

huangapple
  • 本文由 发表于 2023年7月6日 13:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定