问题描述
我正在使用使用MySQL数据库的Django进行Web服务。客户端通过URL处理我们的数据库,由Django处理。现在我正在尝试创建一个行为,每当某个表被修改时自动执行一些检查/记录,这自然就意味着MySQL触发器。但是我也可以在Django中,在修改表的请求处理程序中执行此操作。我不认为Django有触发支持,所以我不知道哪个更好,通过Django代码或MySQL触发器。任何知道性能的人这些选择关心一些光吗?感谢提前!
有很多方法可以解决您所描述的问题:
- 应用程序逻辑
- 查看特定的逻辑 - 如果行为特定于单个视图,则将更改放在视图中。
- 特定于模型的逻辑 - 如果行为特定于单个模型,然后以添加额外的行为,而不改变应用程序本身。
- 数据库存储过程 - 通常是一种可能性,但Django的ORM不使用它们。
- 数据库触发器 - 不能从一个数据库移植到另一个数据库(或甚至数据库的一个版本到下一个),但允许您以控制跨多个(可能非Django)应用程序的共享行为。
个人而言,我更喜欢使用save()或使用Django信号。使用视图特定的逻辑可以捕捉到大型应用程序,具有相同模型的多个视图。
I'm making a web service with Django that uses MySQL database. Clients interface with our database through URLs, handled by Django. Right now I'm trying to create a behavior that automatically does some checking/logging whenever a certain table is modified, which naturally means MySQL triggers. However I can also do this in Django, in the request handler that does the table modification. I don't think Django has trigger support yet, so I'm not sure which is better, doing through Django code or MySQL trigger.
Anybody with knowledge on the performance of these options care to shed some light? Thanks in advance!
解决方案There are a lot of ways to solve the problem you've described:
- Application Logic
- View-specific logic -- If the behavior is specific to a single view, then put the changes in the view.
- Model-specific logic -- If the behavior is specific to a single model, then override the save() method for the model.
- Middleware Logic -- If the behavior relates to multiple models OR needs to wrapped around an existing application, you can use Django's pre-save/post-save signals to add additional behaviors without changing the application itself.
- Database Stored Procedures -- Normally a possibility, but Django's ORM doesn't use them. Not portable across databases.
- Database Triggers -- Not portable from one database to another (or even one version of a database to the next), but allow you to control shared behavior across multiple (possibly non-Django) applications.
Personally, I prefer using either overriding the save() method, or using a Django signal. Using view-specific logic can catch you out on large applications with multiple views of the same model(s).
这篇关于Django代码或MySQL触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!