我注意到,当使用具有多表继承的模型时,Django的post\u save信号的工作方式有一个奇怪的行为。
class Animal(models.Model):
category = models.CharField(max_length=20)
class Dog(Animal):
color = models.CharField(max_length=10)
我有一个名为echo\u category的保存后回调:
def echo_category(sender, **kwargs):
print "category: '%s'" % kwargs['instance'].category
post_save.connect(echo_category, sender=Dog)
我有这个固定装置:
[
{
"pk": 1,
"model": "animal.animal",
"fields": {
"category": "omnivore"
}
},
{
"pk": 1,
"model": "animal.dog",
"fields": {
"color": "brown"
}
}
]
from animal.models import Dog
Dog.objects.get(pk=1).category == u'omnivore' # True
当我运行syncdb并安装了fixture时,echo\u category函数就运行了。syncdb的输出是:
$ python manage.py syncdb --noinput
Installing json fixture 'initial_data' from '~/my_proj/animal/fixtures'.
category: ''
Installed 2 object(s) from 1 fixture(s)
作为一种临时(希望是)解决方法,我在post\u save回调中从数据库重新加载对象:
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)