【发布时间】:2014-06-03 21:27:27
【问题描述】:
我想在 Django 中序列化单个模型的值。因为要使用get(),所以values()不可用。但是,我读过on Google Groups,您可以使用__dict__ 访问这些值。
from django.http import HttpResponse, Http404
import json
from customer.models import Customer
def single(request, id):
try:
model = Customer.objects.get(id=id, user=1)
except Customer.DoesNotExist:
raise Http404
values = model.__dict__
print(values)
string = json.dumps(values)
return HttpResponse(string, content_type='application/json')
print 语句输出这个。
{'_state': <django.db.models.base.ModelState object at 0x0000000005556EF0>, 'web
site': 'http://example.com/', 'name': 'Company Name', 'id': 1, 'logo': '', 'use
r_id': 1, 'address3': 'City', 'notes': '', 'address2': 'Street 123', 'address1': 'Company Name', 'ustid': 'AB123456789', 'fullname': 'Full Name Of Company Inc.', 'mail': 'contact@example.com'}
由于 _state 键包含不可序列化的值,因此下一行失败并出现此错误。
<django.db.models.base.ModelState object at 0x0000000005556EF0> is not JSON serializable
如何在不包含_state 的情况下序列化从__dict__ 返回的字典?
【问题讨论】:
-
@FallenAngel 序列化
all()返回的内容是微不足道的,但我的问题是关于get()。这是相关的,但不是重复的。
标签: python json django dictionary django-1.7