django 返回json

1: querySet-- json.dumps()

class User(object):
   def __init__(self, name):
      self.name = name
class UserEncoder(json.JSONEncoder):
   def default(self, obj):
      if isinstance(obj, User):
         return obj.name
      return json.JSONEncoder.default(self, obj)

json_2 = {'user':User('orangle')}
print json.dumps(json_2, cls=UserEncoder)

2:serializers

https://docs.djangoproject.com/en/dev/topics/serialization/

from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())



from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', some_queryset)
# serialize object
serialized_object = serializers.serialize('json', [some_object,])

http://stackoverflow.com/questions/757022/how-do-you-serialize-a-model-instance-in-django

你可能感兴趣的:(django 返回json)