Django模型中如何JSON序列化__dict__? [英] How to JSON serialize __dict__ of a Django model?
问题描述
get()
, values()
不可用。不过,我阅读了您可以访问值的 Google网上论坛与 __ 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)
除了Customer.DoesNotExist:
raise Http404
values = model .__ dict__
print(values)
string = json.dumps(values)
return HttpResponse(string,content_type ='application / json')
打印语句输出
{'_ state':< django.db.models.base.ModelState对象在0x0000000005556EF0>'web
site':'http://example.com/','name':'公司名称','id':1,'logo':'','使用
r_id' 'address3':'城市','地址2':'街123','地址1':'公司名称','ustid':'AB123456789','全名':'公司名称'邮件':'contact@example.com'}
由于 _state
键持有一个不可序列化的值,下一行失败,出现此错误。
< django.db .models.base.ModelState对象在0x0000000005556EF0>不是JSON序列化
如何序列化从 __ dict __
不包含 _state
model_to_dict()
是你需要的:
from django.forms.models import model_to_dict
data = model_to_dict(model )
data ['logo'] = data ['logo']。url
return HttpResponse(json.dumps(data),content_type ='application / json')
通过指定字段
和排除
关键字参数你可以控制什么字段序列化。
另外,你可以简化 try / except
block通过使用快捷方式 get_object_or_404()
:
model = get_object_or_404(Customer,id = id,user = 1)
I want to serialize the values of a single model in Django. Because I want to use get()
, values()
is not available. However, I read on Google Groups that you can access the values with __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')
The print statement outputs this.
{'_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'}
Because of the _state
key that holds an unserializable value the next line fails with this error.
<django.db.models.base.ModelState object at 0x0000000005556EF0> is not JSON serializable
How can I serialize the dictionary returned from __dict__
without _state
being included?
model_to_dict()
is what you need:
from django.forms.models import model_to_dict
data = model_to_dict(model)
data['logo'] = data['logo'].url
return HttpResponse(json.dumps(data), content_type='application/json')
By specifying fields
and exclude
keyword arguments you can control what fields to serialize.
Also, you can simplify the try/except
block by using the shortcut get_object_or_404()
:
model = get_object_or_404(Customer, id=id, user=1)
这篇关于Django模型中如何JSON序列化__dict__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!