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?
I found out that is is actually possible to use
values()
together withget()
. You just have to fetch values from a filtered set.model_to_dict()
is what you need:By specifying
fields
andexclude
keyword arguments you can control what fields to serialize.Also, you can simplify the
try/except
block by using the shortcutget_object_or_404()
:check the source code django/core/serializers/__init__.py comment:
for one object