python - Django Rest Framework: Including multiple choice fields in Serializer -
i'm using django rest framework create custom api movies
model defined follows:
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)
now, want allow admin of application enter new instances of movies
model api. want genre
field multiple choice field, i.e. admin should able select more 1 genres particular movie.
serializers.py
from shoppy.models import movies 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')
however, @ api endpoint, admin able select 1 genre
given list of choices. know if working forms, how have implemented multiple choices checkbox:
genre = forms.charfield(max_length = 1230, widget=forms.checkboxselectmultiple( choices=movies.genre_choices))
how implement multiple choice fields in serializers, admin chose more 1 genre in api endpoint?
the root issue model:
genre = models.charfield(max_length=128, choices=genre_choices)
your model allows store single value in column hence drf (django rest framework) enforces same restrictions in api. if want users able select multiple genres, easiest solution introduce genres
model movies
have m2m relationship:
class genres(models.model): genre = models.charfield(unique=true) class movies(models.model): genres = manytomanyfield(genres, related_name='movies')
Comments
Post a Comment