我有以下Django模型
class ConfigurationItem(models.Model):
path = models.CharField('Path', max_length=1024)
name = models.CharField('Name', max_length=1024, blank=True)
description = models.CharField('Description', max_length=1024, blank=True)
active = models.BooleanField('Active', default=True)
is_leaf = models.BooleanField('Is a Leaf item', default=True)
class Location(ConfigurationItem):
address = models.CharField(max_length=1024, blank=True)
phoneNumber = models.CharField(max_length=255, blank=True)
url = models.URLField(blank=True)
read_acl = models.ManyToManyField(Group, default=None)
write_acl = models.ManyToManyField(Group, default=None)
alert_group= models.EmailField(blank=True)如果有帮助,完整的模型文件是here。
您可以看到,Company是ConfigurationItem的子类。
我正在尝试使用django.core.serializers.serializer或WadofStuff序列化程序来使用JSON序列化。
这两个序列化程序都给了我同样的问题...
>>> from cmdb.models import *
>>> from django.core import serializers
>>> serializers.serialize('json', [ ConfigurationItem.objects.get(id=7)])
'[{"pk": 7, "model": "cmdb.configurationitem", "fields": {"is_leaf": true, "extension_attribute_10": "", "name": "", "date_modified": "2010-05-19 14:42:53", "extension_attribute_11": false, "extension_attribute_5": "", "extension_attribute_2": "", "extension_attribute_3": "", "extension_attribute_1": "", "extension_attribute_6": "", "extension_attribute_7": "", "extension_attribute_4": "", "date_created": "2010-05-19 14:42:53", "active": true, "path": "/Locations/London", "extension_attribute_8": "", "extension_attribute_9": "", "description": ""}}]'
>>> serializers.serialize('json', [ Location.objects.get(id=7)])
'[{"pk": 7, "model": "cmdb.location", "fields": {"write_acl": [], "url": "", "phoneNumber": "", "address": "", "read_acl": [], "alert_group": ""}}]'
>>>问题是,序列化Company模型只给出了与该模型直接关联的字段,而不是来自其父对象的字段。
有没有办法改变这种行为,或者我是否应该考虑构建一个对象字典并使用simplejson来格式化输出?
提前感谢
~sm
发布于 2013-01-15 23:41:03
对于最初的发帖者来说,这是答案可能来得太晚了,但对于下一位谷歌人来说,答案可能会派上用场。
如果您需要更高级的序列化,我无能为力,但是如果您只想优雅地处理多表继承,那么可以在Serializer基类的django/core/serializers/base.py中查找。
在serialize方法中有一行:
for field in concrete_model._meta.local_fields:
Monkeypatching或覆盖该类&将该行替换为:
for field in concrete_model._meta.fields:
但是,有一些需要注意的事项,请参阅Django Git代码库中的commit 12716794db &这两个问题:
https://code.djangoproject.com/ticket/7350
https://code.djangoproject.com/ticket/7202
长话短说,您可能应该小心在全局范围内执行此操作,尽管根据您的目标覆盖该行为可能会很好。
发布于 2018-07-17 15:43:25
也许现在已经很晚了,但我给出了我的解决方案,以防它会有用。我使用了另一个Django库来完成这项工作:
from django.forms.models import model_to_dict
model_to_dict(Location.objects.get(id=7), fields = ['name', 'address', 'phoneNumber'])
model_to_dict(Location.objects.get(id=7))您可以指定或不指定字段列表。我试过我的一个模型,它对我来说工作得很好。唯一的区别是,在输出中,您将只获得字段值,而不是模型信息。
https://stackoverflow.com/questions/2866105
复制相似问题