2

Django has middleware to achieve do somthing when request and response. Is Django has "database middleware" to achieve do somthing when write data and read data.

For example,some old database does not support to utf8mb4 , so it can't support all of emoji. If Django has "database middleware" I will encode data when it is being saved , And decode when it is being reading.

cyhhao
  • 55
  • 6
  • I don't answer your question, but perhaps I can help you with another approach. There is a new feature in the upcoming django [utf8mb4 encoding with MySQL 5.5](https://code.djangoproject.com/ticket/18392). Meanwhile the people there are discussing an alternative solution for the moment. :) – Yeo May 05 '15 at 14:00
  • You should check out [django signals](https://docs.djangoproject.com/en/1.8/topics/signals/). You can call functions pre and post save from any database model, essentially being a middleware. – Jordan May 05 '15 at 14:01
  • If you really want to go deeper into implementing this solution, perhaps you could dig into the source code how they implement the [DB backend](https://github.com/django/django/tree/master/django/db/backends) – Yeo May 05 '15 at 14:02
  • Perhaps this might help if you are already good in Django. [James Bennett Django in Depth](https://youtu.be/tkwZ1jG3XgA?t=4m38s). Brace yourself it is 3hours but you just need to watch the next 1 hour for your problem. – Yeo May 05 '15 at 14:05
  • @Yeo Thank you very much~ It is a pity I think I'm not good in Django . Maybe I will read it in the near future. – cyhhao May 05 '15 at 14:28

1 Answers1

0

You can overwrite model methods specially save method to achieve this.

Example from docs from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        # your intended modification
        do_something()
        super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
        do_something_else()

Also check pre_save and post_save Model signals.

moonstruck
  • 2,729
  • 2
  • 26
  • 29
  • does not cover the `decode` part when it was being `read` from the database. – Yeo May 05 '15 at 14:08
  • @Yeo Django Model Descriptors is a good candidate to solve this. [Good explanation here](http://blog.kevinastone.com/django-model-descriptors.html) – moonstruck May 10 '15 at 01:13