Django序列化继承的模型 [英] Django serialization of inherited model
问题描述
class Animal(models.Model):
color = models.CharField(max_length = 50)
class Dog(Animal):
name = models.CharField(max_length = 50)
...
#现在我想序列化狗模型动物遗传领域显然包括
print serializers.serialize('xml',Dog.objects.all())
只有狗模型已经序列化。
我可以像
all_objects = list(Animal.objects.all())+ list(Dog.objects.all())
print serializers.serialize('xml',all_objects)
但它看起来很丑陋,因为我的模型非常大,所以我必须使用SAX解析器,这样的输出很难解析
任何想法如何使用父类序列化django模型?
**编辑:**使用在此之前修补程序已被应用。并且解释为什么补丁存在模型保存对于在反序列化过程中创建新的父类实例太过于激进了,原型保存在模型上现在跳过了父类的保存我认为应该有一个选项可以序列化本地字段,第二个选项 - 全部 - 序列化所有继承的字段。
all_objects = list(Animal.objects.all())+ list(Dog.objects.all( ))
print serializers.serialize('xml',all_objects)
但是,如果你更改动物
成为一个抽象的基类,它将工作:
类动物(models.Model):
color = models.CharField(max_length = 50)
class Meta:
abstract = True
class Dog动物):
name = models.CharField(max_length = 50)
这个工作与Django 1.0一样。请参阅 http://docs.djangoproject.com/en/dev/topics/ db / models / 。
I have a problem with serialization of Django inherited models. For example
class Animal(models.Model):
color = models.CharField(max_length=50)
class Dog(Animal):
name = models.CharField(max_length=50)
...
# now I want to serialize Dog model with Animal inherited fields obviously included
print serializers.serialize('xml', Dog.objects.all())
and only Dog model has been serialized.
I can do smth like
all_objects = list(Animal.objects.all()) + list(Dog.objects.all())
print serializers.serialize('xml', all_objects)
But it looks ugly and because my models are very big so I have to use SAX parser and with such output it's difficult to parse.
Any idea how to serialize django models with parent class?
**EDIT: ** It use to work ok before this patch has been applied. And the explanation why the patch exist "Model saving was too aggressive about creating new parent class instances during deserialization. Raw save on a model now skips saving of the parent class. " I think there should be an option to be able to serialize "local fields only" by default and second option - "all" - to serialize all inherited fields.
You found your answer in the documentation of the patch.
all_objects = list(Animal.objects.all()) + list(Dog.objects.all())
print serializers.serialize('xml', all_objects)
However, if you change Animal
to be an abstract base class it will work:
class Animal(models.Model):
color = models.CharField(max_length=50)
class Meta:
abstract = True
class Dog(Animal):
name = models.CharField(max_length=50)
This works as of Django 1.0. See http://docs.djangoproject.com/en/dev/topics/db/models/.
这篇关于Django序列化继承的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!