其他分享
首页 > 其他分享> > 如何JSON序列化Django模型的__dict__?

如何JSON序列化Django模型的__dict__?

作者:互联网

我想在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__返回的字典?

解决方法:

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')

通过指定字段和排除关键字参数,您可以控制要序列化的字段.

此外,您可以使用快捷方式get_object_or_404()简化try / except块:

model = get_object_or_404(Customer, id=id, user=1)

标签:python,json,dictionary,django,django-1-7
来源: https://codeday.me/bug/20191005/1857496.html