Django Rest Framework:在Serializer中包含多个选择字段

时间:2015-07-13 23:25:52

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

我正在使用Django Rest Framework为我的Movies模型创建一个自定义API,其定义如下:

models.py

from django.db import models

class Movies(models.Model):
    popularity = models.FloatField()
    director = models.CharField(max_length = 128)
    GENRE_CHOICES = (('Adventure', 'Adventure'), ('Family', 'Family'), ('Fantasy', 'Fantasy'),
                        ('Musical', 'Musical'), ('Sci-Fi', 'Sci-Fi'), ('Drama', 'Drama'), ('War', 'War'),
                            ('Romance', 'Romance'), ('Comedy', 'Comedy'), ('Thriller', 'Thriller'),
                                ('Crime', 'Crime'), ('Horror', 'Horror'), ('History', 'History'), ('Family', 'Family'),
                                    ('Animation', 'Animation'), ('Short', 'Short'), ('Western', 'Western'),
                                        ('Action', 'Action'), ('Biography', 'Biography'))
    genre = models.CharField(max_length = 128, choices = GENRE_CHOICES)
    imdb_score = models.FloatField()
    movie_name = models.CharField(max_length = 500)

现在,我想允许应用程序的管理员在API中输入Movies模型的新实例。我希望genre字段是一个多选字段,即管理员应该能够为特定电影选择多个类型。

serializers.py

from shoppy.models import Movies
from rest_framework import serializers


class MoviesSerializer(serializers.ModelSerializer):
    #genre = serializers.CharField(max_length = 128, choices = Movies.GENRE_CHOICES)

    class Meta:
        model = Movies
        fields = ('popularity', 'director', 'genre', 'imdb_score',
                        'movie_name')

但是,在API端点,管理员只能从给定的选择列表中选择一个genre。我知道,如果我正在使用表单,这就是我实现多选项复选框的方式:

genre = forms.CharField(max_length = 1230, widget=forms.CheckboxSelectMultiple(
                                                    choices=Movies.GENRE_CHOICES))

如何在Serializers中实现多选字段,以便管理员可以在API端点中选择多个类型?

1 个答案:

答案 0 :(得分:1)

根本问题在于您的模型:

genre = models.CharField(max_length=128, choices=GENRE_CHOICES)

您的模型只允许在该列中存储单个值,因此DRF(Django Rest Framework)在API中强制执行相同的限制。如果您希望用户能够选择多种类型,最简单的解决方案是引入Genres模型,Movies将具有m2m关系:

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

class Movies(models.Model):
    genres = ManyToManyField(Genres, related_name='movies')