Django code or MySQL triggers

I am doing a web service with Django that uses a MySQL database. Clients interact with our database through the URLs processed by Django. Now I am trying to create a behavior that automatically performs some check / registration whenever a certain table changes, which naturally means MySQL triggers. However, I can do this in Django, in the query handler that modifies the table. I donโ€™t think Django has trigger support, so Iโ€™m not sure if itโ€™s better to do MySQL through a Django code or trigger.

Can anyone with knowledge of these options shed light? Thanks in advance!

+4
source share
2 answers

There are many ways to solve this problem:

  • Application logic
    • View-specific logic . If the behavior refers to only one view, make changes to the view.
    • Model specific logic . If the behavior applies to only one model, override the save () method for the model.
  • Middleware logic - if the behavior applies to several models OR needs to be wrapped around an existing application, you can use Django signals before / after saving to add additional behaviors without changing the application itself.
  • Procedures stored in the database - This is usually possible, but Django ORM does not use them. Not migrated between databases.
  • Database triggers are not portable from one database to another (or even from one version of the database to another), but they allow you to control the general behavior of several applications (possibly not Django).

Personally, I prefer to either override the save () method or use the Django signal. Using logic for specific representations can help you in large applications with multiple representations of the same model.

+8
source

What you describe sounds like "change data capture."

I think compromises might look like this:

  • Django pros: mid-level code can be used by several applications; portable if changes to the database
  • Django cons: Logically is not part of a business transaction.
  • MySQL Benefits: Naturally doing this in a database
  • MySQL minus: triggers are very specific for a particular database; if you change suppliers you need to rewrite

This may be helpful.

0
source

Source: https://habr.com/ru/post/897909/


All Articles