A note on django signal pre_save

/, Python/A note on django signal pre_save

A note on django signal pre_save

I am testing on django signal pre_save, and I want to share a note on this.

This is my example code.

# -*- coding: utf-8 -*-
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

class Parameter(models.Model):
Tabla de parametros, clave valor.
def __init__(self, *args, **kwargs):
super(Parameter, self).__init__(*args, **kwargs)
self.__original_value = self.value

def save(self, force_insert=False, force_update=False, *args,**kwargs):
if self.value != self.__original_value:
super(Parameter, self).save(force_insert, force_update, *args, **kwargs)
self.__original_value = self.value

key = models.CharField(max_length=24, db_index=True, unique=True)
value = models.CharField(max_length=128)

def __unicode__(self):
return u'[%s] %s'%(self.key, self.value)
def __str__(self):
return '[{a}] {b}'.format(a=self.key, b=self.value)

class Meta:
app_label = 'parameter'

def save_param(sender, instance, **kwargs):
import pdb;pdb.set_trace()
g = 2
return 0


If you do not know about signals, you can make a quick google search.

If you know, pre_save is sent before save() … but what happens if we override save.

Here I want to detect a change of value, and see what happens.

$ ./manage.py shell_plus

>>> p = Parameter.objects.get(key="aa")
>>> p.value
>>> p.value="dd"
>>> p.save()
> /home/gamadio/back_emedido/back_emedido/apps/parameter/models.py(35)save_param()
-> g = 2

You can see "caamaan" was printed before the PDB, I mean receiver function.

So Be Aware Of That! =D

By |2018-04-24T19:38:07+00:00abril 24th, 2018|Categories: Django, Python|Tags: |1 Comment

About the Author:

One Comment

  1. gonzalo abril 26, 2018 at 4:20 am - Reply

    Gracias Dani, que bueno que te han gustado

Leave A Comment