[Answer]-Django – Natural key serialization of User

1πŸ‘

βœ…

I assume you’re serializing your model in order to transmit it on wire (like in a http response).

django.core.serializers is likely not the way you want to go. A quick approach would be to include a method on the model to return the dictionary you want to be serialized, then use simplejson.dumps to serialize it. E.g.:

def to_json(self):
    return dict(
        author=[self.author.natural_key(), self.author.first_name, self.author.last_name],
        text=self.text,
    )

then just call simplejson.dumps(comment.to_json()).

πŸ‘€Davide R.

Leave a comment