Alex
Alex

Reputation: 6037

Django serializer get related field

I have a querySet that I want to turn into a json and send to the client. It only needs some of the fields, as defined. However, the 'sender' shows up as a id because it is a foreignKey.

What would be needed to return the senders username instead? (sender.username didn't work). (Not using drf)

messages = Message.objects.all()
messages_json = serializers.serialize("json", messages, fields=('id','sender', 'text', 'timestamp'))

Upvotes: 0

Views: 223

Answers (2)

Alex
Alex

Reputation: 6037

I think I've found a way so I'll answer it myself

from django.core.serializers.python import Serializer

class MySerialiser(Serializer):
    def end_object( self, obj ):
        self._current['username'] = obj.sender.username
        self.objects.append(self._current)

serializer = MySerialiser()
messages_ser  = serializer.serialize(messages, fields=('id','sender','text' ))
messages_json = json.dumps(messages_ser)

messages_ser is a orderedDict, so turning it into json only works when there are no nested objects/dicts

Upvotes: 0

Steve Jalim
Steve Jalim

Reputation: 12195

Not tested but using QuerySet.values and __ relations-walking lets you get the data in one hit:

import json

messages = Message.objects.all()
payload_data = messages.values('id', 'sender__username', 'text', 'timestamp')

# tidy up the dict key names, assuming the client needs that doing
for x in payload_data:
    x['sender'] = x['sender__username']
    del x['sender__username']

messages_json = json.dumps(payload_data)

Upvotes: 1

Related Questions