[英]How to JSON serialize __dict__ of a Django model?
I want to serialize the values of a single model in Django. 我想序列化Django中单个模型的值。 Because I want to use
get()
, values()
is not available. 因为我想使用
get()
,所以values()
不可用。 However, I read on Google Groups that you can access the values with __dict__
. 但是,我在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)
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. 由于
_state
密钥拥有无法序列化的值,因此下一行会因该错误而失败。
<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? 如何在不包含
_state
情况下序列化从__dict__
返回的字典?
model_to_dict()
is what you need: 您需要
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')
By specifying fields
and exclude
keyword arguments you can control what fields to serialize. 通过指定
fields
并exclude
关键字参数,您可以控制要序列化的字段。
Also, you can simplify the try/except
block by using the shortcut get_object_or_404()
: 另外,您可以使用快捷方式
get_object_or_404()
来简化try/except
块:
model = get_object_or_404(Customer, id=id, user=1)
check the source code django/core/serializers/ __init__ .py comment: 检查源代码django / core / serializers / __init__ .py注释:
Interfaces for serializing Django objects.
Usage::
from django.core import serializers
json = serializers.serialize("json", some_queryset)
objects = list(serializers.deserialize("json", json))
To add your own serializers, use the SERIALIZATION_MODULES setting::
SERIALIZATION_MODULES = {
"csv" : "path.to.csv.serializer",
"txt" : "path.to.txt.serializer",
}
for one object 对于一个对象
json = serializers.serialize("json", some_queryset[0:1])
I found out that is is actually possible to use values()
together with get()
. 我发现实际上可以将
values()
与get()
一起使用。 You just have to fetch values from a filtered set. 您只需要从经过过滤的集合中获取值即可。
def single(request, id):
user = 1
try:
models = Customer.objects.filter(id=id, user=user)
values = models.values().get()
except Customer.DoesNotExist:
raise Http404
string = json.dumps(values)
return HttpResponse(string, content_type='application/json')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.