Jaco
Jaco

Reputation: 1694

Django: return value and not key when serialize a foreign field in DRF

I'd like to ask how I can get the ForeignKey (or ManyToManyField) text value to show up in a GET request.

Below will produce a JSON with keys referring to either choices or ForeignKey

[
    {
        "album_name": "Album_1",
        "grade": "1",
        "artist": 2
    }
]

but I'd like it to display

[
    {
        "album_name": "Album_1",
        "grade": "Bad",
        "artist": "Artist_name_NN"
    }
]

Those examples I find related to ForeignKey, either on Django Rest Framworks own site or at SO or through various blog posts are not very clear cut and tend to complicate an explanation/solution by also using indirect relationships.

I am looking for a minimum viable solution for values to come up in a GET request given below setup.

## Models.py
class Artist(models.Model):
    artist_name = models.CharField(max_length=100)
    comment = models.CharField(max_length=100)

    def __str__(self):
        return (self.artist_name)

class Album(models.Model):
    GRADE = (
        ("1", "Bad"),
        ("2", "Average"),
        ("3", "Good"),
    )
    album_name = models.CharField(max_length=100)
    grade = models.CharField(max_length=100, choices=GRADE)
    artist = models.ForeignKey(Artist, blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return (self.album_name)

## views.py
class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

## Serializers.py
class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        model = Album
        fields = ['album_name', 'grade', 'artist']

Upvotes: 1

Views: 830

Answers (1)

Robert Kearns
Robert Kearns

Reputation: 1706

A good example of this is found in the serializer relations section of the drf documentation.

You can achieve what you want with a StringRelatedField. For example:

class AlbumSerializer(serializers.ModelSerializer):
    
    artist = serializers.StringRelatedField()

    class Meta:
        model = Album
        fields = ['album_name', 'grade', 'artist']

This will use the __str__ method on the artist to fill the field.

Upvotes: 3

Related Questions