django serializers to json - custom json output format
django, json, python
Solution
You can add 'fields' parameter to the serialize-function, like this:
data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
See: https://docs.djangoproject.com/en/dev/topics/serialization/
EDIT 1:
You can customize the serializer to get only the fields you specify.
From Override Django Object Serializer to get rid of specified model:
from django.core.serializers.python import Serializer
class MySerialiser(Serializer):
def end_object( self, obj ):
self._current['id'] = obj._get_pk_val()
self.objects.append( self._current )
# views.py
serializer = MySerialiser()
data = serializer.serialize(some_qs)
Problem
I am quite new to django and recently I have a requirement of a JSON output, for which I use the following django code: ``` data = serializers.serialize("json", Mymodel.objects.all()) ``` It works great, except that I get a output of: ``` [{"pk": 8970859016715811, "model": "myapp.mymodel", "fields": {"reviews": "3.5", "title": .....}}] ``` However, I would like the output to be simply either: ``` [{"reviews": "3.5", "title": .....}] ``` or, ``` [{"id": "8970859016715811", "reviews": "3.5", "title": .....}] ``` I was wondering if someone could point me to the right direction as to how to achieve this.