我的应用程序包含两个不同的模型,与多对多关系相关,如下所示:
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')
这就是http://localhost:8000/movies/
处的API端点形式:
现在,我不是将genres
显示为Genres
对象编号的实例,而是如何使它们显示为与每个对象编号对应的实际字符串?例如,Genres object-1
对应Comedy
,这就是我希望在API端点表单中显示的内容,以使类型选择更具人性化。
做出类似事情的方式是什么?
答案 0 :(得分:2)
您需要在__str__
模型中实施Genres
方法。
class Genres(models.Model):
genre = models.CharField(max_length = 128, unique = True)
def __str__(self):
return '%s'%self.genre