Django post_save signal behaves strangely with models using multiple table inheritance
I notice strange behavior in the way the Django post_save signal works when using a model with overlapping multiple tables.
I have two models:
class Animal(models.Model): category = models.CharField(max_length=20) class Dog(Animal): color = models.CharField(max_length=10)
I have a response to saving a message called echo_category:
def echo_category(sender, **kwargs): print "category: '%s'" % kwargs['instance'].category post_save.connect(echo_category, sender=Dog)
I have this device:
[ { "pk": 1, "model": "animal.animal", "fields": { "category": "omnivore" } }, { "pk": 1, "model": "animal.dog", "fields": { "color": "brown" } } ]
In each part of the program, except in the post_save callback, the following is true:
from animal.models import Dog Dog.objects.get(pk=1).category == u'omnivore'
When I run syncdb and install the device, the echo_category function is launched. Syncdb Output:
$ python manage.py syncdb --noinput Installing json fixture 'initial_data' from '~/my_proj/animal/fixtures'. category: '' Installed 2 object(s) from 1 fixture(s)
It is strange that the attribute of the category of dog objects is an empty string. Why is it not βomnivorous,β like everywhere else?
As a temporary (hopefully) workaround, I reload the object from the database in the post_save callback:
def echo_category(sender, **kwargs): instance = kwargs['instance'] instance = sender.objects.get(pk=instance.pk) print "category: '%s'" % instance.category post_save.connect(echo_category, sender=Dog)
This works, but itβs not what I like, because I have to keep this in mind when the model is inherited from another model, and it has to go back to the database. Another weird thing that I have to do instance.pk to get the primary key. The regular id attribute does not work (I cannot use instance.id). I do not know why this is so. Maybe this is due to why the category attribute is not working correctly?