[Fixed]-Is there a way to choose a specific representation when serializing a `ForeignKey`?

1πŸ‘

βœ…

I hope I understood you correctly.

The proper way to do this would be:

for post in Post.objects.values('id', 'name', 'author__username'):
    ...

This will, without the additional queries your current code would incur, add give you post['author__username'].

Although, since you’re writing a RESTy framework, you probably care about the naming of the keys. Honestly, I have no better solution than this:

for post in ...:
    post['author'] = post['author__username']
    del post['author__username']
πŸ‘€Yotam Ofek

Leave a comment