2

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?

1 Answer 1

5

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')
Sign up to request clarification or add additional context in comments.

1 Comment

I've learned in my years I have a problem with RTFM. Thanks for this exactly what I wanted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.