How to JSON serialize __dict__ of a Django model?

…衆ロ難τιáo~ 提交于 2019-11-30 13:01:46

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)

check the source code django/core/serializers/__init__.py comment:

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(). 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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!