Django Rest Framework:将模型对象编号转换为其对应的字符串

时间:2015-07-14 18:49:27

标签: python django rest python-2.7 django-rest-framework

我的应用程序包含两个不同的模型,与多对多关系相关,如下所示:

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端点形式:

enter image description here

现在,我不是将genres显示为Genres对象编号的实例,而是如何使它们显示为与每个对象编号对应的实际字符串?例如,Genres object-1对应Comedy,这就是我希望在API端点表单中显示的内容,以使类型选择更具人性化。

做出类似事情的方式是什么?

1 个答案:

答案 0 :(得分:2)

您需要在__str__模型中实施Genres方法。

class Genres(models.Model):
    genre = models.CharField(max_length = 128, unique = True)

    def __str__(self):
        return '%s'%self.genre