英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论