Reputation: 2583
Suppose I have a model of a comment in my project:
class Comment(models.Model):
text = models.TextField(max_length=500, blank=False)
author = models.ForeignKey(User)
When serialized to JSON using django.core.serializers
the author field comes out as:
"author": 1 // use_natural_keys = False
"author": ["someuser"] // use_natural_keys = True
Suppose I want to output the user's first and last name as well? How would I go about that?
Upvotes: 0
Views: 1284
Reputation: 900
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())
.
Upvotes: 1