How to JSON serialize __dict__ of a Django model?

后端 未结 3 1773
北荒
北荒 2021-01-02 08:31

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 ca

3条回答
  •  悲&欢浪女
    2021-01-02 09:06

    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)
    

提交回复
热议问题