Reputation: 5550
I've an application which contains two different models, related by a Many-to-Many relationship as follows:
from django.db import models
class Genres(models.Model):
genre = models.CharField(max_length = 128, unique = True)
class Movies(models.Model):
popularity = models.FloatField()
director = models.CharField(max_length = 128)
genre = models.ManyToManyField(Genres, related_name = 'movies')
imdb_score = models.FloatField()
movie_name = models.CharField(max_length = 500)
serializers.py
from shoppy.models import Movies, Genres
from rest_framework import serializers
class GenresSerializer(serializers.ModelSerializer):
class Meta:
model = Genres
fields = ('genre',)
class MoviesSerializer(serializers.ModelSerializer):
#genre = serializers.CharField(max_length = 128, choices = Movies.GENRE_CHOICES)
class Meta:
model = Movies
fields = ('popularity', 'director', 'imdb_score', 'genre',
'movie_name')
This is how my API endpoint form at http://localhost:8000/movies/
looks like:
Now, instead of different genres
appearing as instances of Genres
object numbers, how can I make them appear as the actual string corresponding to each object number? For example, Genres object-1
corresponds to Comedy
, and that is what I want to be displayed in the API endpoint form to make the genre choices more human-readable.
What's the way to do something like that?
Upvotes: 0
Views: 1331
Reputation: 47896
You need to implement a __str__
method in your Genres
model.
class Genres(models.Model):
genre = models.CharField(max_length = 128, unique = True)
def __str__(self):
return '%s'%self.genre
Upvotes: 2