Sim*_*ris 4 python django json jsonserializer
我有以下 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)
Run Code Online (Sandbox Code Playgroud)
如果有帮助,完整的模型文件在这里。
您可以看到 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": ""}}]'
>>>
Run Code Online (Sandbox Code Playgroud)
问题是序列化 Company 模型只会给我与该模型直接关联的字段,而不是来自它的父对象的字段。
有没有办法改变这种行为,或者我应该考虑构建一个对象字典并使用 simplejson 来格式化输出?
提前致谢
~sm
这是对原始海报来说答案可能为时已晚的时候之一,但可能对下一个 Google 员工派上用场。
如果您需要更高级的序列化,我无法帮助您,但如果您只想优雅地处理多表继承,则可以查看:django/core/serializers/base.py在Serializer基类中。
在serialize方法中有一行:
for field in concrete_model._meta.local_fields:
Monkeypatching 或覆盖该类并将该行替换为:
for field in concrete_model._meta.fields:
但是,有一些注意事项需要注意,请参阅 Django Git repo 中的 commit 12716794db 和这两个问题:
https://code.djangoproject.com/ticket/7350
https://code.djangoproject.com/ticket/7202
长话短说,您可能应该小心在全局范围内执行此操作,尽管根据您的目标覆盖该行为可能没问题。
| 归档时间: |
|
| 查看次数: |
2246 次 |
| 最近记录: |