codecrazy46
codecrazy46

Reputation: 297

How to save a ManyToMany Field as a value instead of id

I have the below models and serializers with a ManyToMany relationship between movies and genres. However when I select the genres for a movie with an api, the movie is getting saved with the genre id instead of the genre name. How can I make it save with the genre name instead of id.

Models.py:

class Genre(models.Model):
    genre = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.genre

class Movie(models.Model):
    name = models.CharField(max_length=50)
    release_date = models.DateField()
    genre = models.ManyToManyField(Genre, related_name='movie')

Serializers.py

class GenreSerializer(ModelSerializer):
    class Meta:
        model = Genre
        fields = (genre, )

class MovieSerializer(ModelSerializer):
    class Meta:
        model = Movie
        fields = ('id', 'name', 'release_date', 'genre', )

I have 3 genres as below inserted through API: 1. Horror 2. Comedy 3. Animation

When I saved a movie named 'Scary Movie' with the genres Horror and Comedy, its getting saved as below with the genre ids instead of their values i.e. Horror and Comedy:

On using the below api to list all the saved movies, it shows as below /api/movie

{
    "id": 1
    "name": "Scary Movie",
    "release date": 2000-07-13,
    "genre": [
    1,
    2
]
}

How can I make the movie saved with genre name instead of genre id?

Upvotes: 2

Views: 1124

Answers (1)

Stevy
Stevy

Reputation: 3387

You can use a nested serializer like this:

class GenreSerializer(ModelSerializer):
    class Meta:
        model = Genre
        fields = (genre,)

class MovieSerializer(ModelSerializer):
    genre = GenreSerializer(many=True)

    class Meta:
        model = Movie
        fields = ('id', 'name', 'release_date', 'genre')

This should result in:

 [
    {
        "id": 1
        "name": "Scary Movie",
        "release date": 2000-07-13,
        "genre": [
            {
                "genre": "Horror"
            },
            {
                "genre": "Comedy"
            }
        ]
    }, ...
]

Upvotes: 3

Related Questions