这个 JSON 序列化器应该可以工作:
from StringIO import StringIO
from django.core.serializers.json import Serializer
class JSONSerializer(Serializer):
def serialize(self, queryset, attributes, **options):
self.options = options
self.stream = options.get("stream", StringIO())
self.start_serialization()
self.first = True
for obj in queryset:
self.start_object(obj)
for field in attributes:
self.handle_field(obj, field)
self.end_object(obj)
if self.first:
self.first = False
self.end_serialization()
return self.getvalue()
def handle_field(self, obj, field):
self._current[field] = getattr(obj, field)
(基于此答案,由Tim Edgar ^发布并使用此要点进行更改)
用法:
json = JSONSerializer().serialize(modelName.objects.all(), ('attr1', 'property1', ...))