Michael
Michael

Reputation: 3608

Django JSON Serialization with Mixed Django models and a Dictionary

I can't seem to find a good way to serialize both Django Models and Python dictionaries together, its pretty common for me to return a json response that looks like

{
  "modified":updated_object,
  "success":true
  ... some additional data...
}

Its simple enough to use either simplejson to serialize a dict or Django's serializers.serialize to serialize a model but when I mix them together I get errors.

Is there a better way to do this?

Upvotes: 4

Views: 2777

Answers (2)

whncode
whncode

Reputation: 429

I'm using this (where products is queryset):

response = {}
products_list = list(products.values('id', 'name', 'description'))
response['products'] = products_list
response['more_data'] = 'more, more, more, things'

json_data = json.dumps(response)

Using this method you can select only fields you want (make json, and database query smaller).

Upvotes: 2

cethegeek
cethegeek

Reputation: 6394

Can't you just convert the model instance to a dict, join the other dict and then serialize?

from django.forms import model_to_dict

dict = model_to_dict(instance)
dict.update(dict2)

... Then serialize here ...

Don't know about being "better"... :-)

Upvotes: 10

Related Questions