whoisearth
whoisearth

Reputation: 4170

django rest framework serializer return name not integer

I'm doing a simple list view where the current return looks like this -

[
    {
        "name": "John",
        "description": "John's Group",
        "owner": 1
    }
]

The problem is I don't want that integer I want it to show like this -

[
    {
        "name": "John",
        "description": "John's Group",
        "owner": "John Smith"
    }
]

The only way around this I have found is to do a serializer like this -

class ClassListSerializer(serializers.ModelSerializer):
    ownername = serializers.CharField(source='owner.username')
    class Meta:
        model=ClassList
        fields = ('name', 'description', 'ownername')

The problem is that I don't want to have to change the field to ownername.

Setting the following in the model works for traditional querying of the model -

def __str__(self):
    return self.username

But I guess because DRF reads differently it doesn't adhere to the ForeignKey mapping and return?

Doing this doesn't work because it's trying to override owner with owner that already exists -

class ClassListSerializer(serializers.ModelSerializer):
    owner = serializers.CharField(source='owner.username')
    class Meta:
        model=ClassList
        fields = ('name', 'description', 'owner')

So how do I get it to display the name instead of the integer?

Upvotes: 2

Views: 814

Answers (1)

Linovia
Linovia

Reputation: 20996

SlugRelatedField are exactly what you're looking for:

class ClassListSerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(
        slug_field='username',
        queryset=User.objects.all())
    class Meta:
        model=ClassList
        fields = ('name', 'description', 'owner')

Upvotes: 5

Related Questions