事情自2010年以來有所改變,所以@ user85461的答案似乎不再適用於Django 1.8和Python 3.4。這是一個更新的答案,似乎對我有用。
from django.core.serializers.base import Serializer as BaseSerializer
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.json import Serializer as JsonSerializer
from django.utils import six
class ExtBaseSerializer(BaseSerializer):
""" Abstract serializer class; everything is the same as Django's base except from the marked lines """
def serialize(self, queryset, **options):
self.options = options
self.stream = options.pop('stream', six.StringIO())
self.selected_fields = options.pop('fields', None)
self.selected_props = options.pop('props', None) # added this
self.use_natural_keys = options.pop('use_natural_keys', False)
self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False)
self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False)
self.start_serialization()
self.first = True
for obj in queryset:
self.start_object(obj)
concrete_model = obj._meta.concrete_model
for field in concrete_model._meta.local_fields:
if field.serialize:
if field.rel is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_field(obj, field)
else:
if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
self.handle_fk_field(obj, field)
for field in concrete_model._meta.many_to_many:
if field.serialize:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_m2m_field(obj, field)
# added this loop
if self.selected_props:
for field in self.selected_props:
self.handle_prop(obj, field)
self.end_object(obj)
if self.first:
self.first = False
self.end_serialization()
return self.getvalue()
# added this function
def handle_prop(self, obj, field):
self._current[field] = getattr(obj, field)
class ExtPythonSerializer(ExtBaseSerializer, PythonSerializer):
pass
class ExtJsonSerializer(ExtPythonSerializer, JsonSerializer):
pass
用法:
>>> ExtJsonSerializer().serialize(MyModel.objects.all(), fields=['myfield', ...], props=['myprop', ...])
這需要基本創造我自己的哈希,只連載基本上哈希。如果我走這條路線,我幾乎可以切斷整個系列化。 我一直希望繼續使用django Model類,並簡單地調用serialize('json',my_object,...) – ashchristopher 2010-04-07 03:29:36
不幸的是,似乎Django的核心序列化例程明確排除了不在_meta中的任何東西基本上只查找數據庫模型字段。所以,雖然你可以寫出一個功能,只拉出屬性字段(這可能會更好地完成「檢查」。getmembers'方法在第二次腮紅時),即使使用'serializers.serialize'方法的'fields'參數也不起作用。 看到這裏,他們在迭代傳入的查詢集,只查找'_meta'中的內容:http://code.djangoproject.com/browser/django/trunk/django/core/serializers/base.py# L39 – 2010-04-07 14:55:09