Remove pk field from django serialized objects

Viewed 14868

I'm serializing a bunch of objects with:

json = serializers.serialize("json", objects, fields=('name', 'country'))

I have not included 'pk' in my fields list, but the produced JSON includes a primary key with each serialized object. I do not want my API to expose primary keys to the general public.

Short of munging the output JSON, what is the correct way to tell serializers.serialze() to not include the primary key?

7 Answers

Although this is an old question, someone else will probably come up with it on a Google search.

Unfortunately the django serializer offers fairly little customization like what you defined. My solution, if you know you will be using a lot of serialization for your project, was simply to copy django's serialization stuff over to my own project and make some small changes. This isn't ideal, but it does the job. Specifically, to remove the pk's, there is a line in start_object(self, obj):

self.xml.startElement("object", {
        "pk"    : smart_unicode(obj._get_pk_val()),
        "model" : smart_unicode(obj._meta),
    })

Removing the "pk" line should fix it. It's a somewhat dirty hack, since if they improve this later on it may require some changes to your views, but for me this was the easiest way around the limitations.

Hope this helps someone.

Related