python - django rest framework how to add entries for multiple tables with one request? -
i'm trying add genres genre model @ same time adding movie movie model, following response object when trying add genre entry doesn't exist (works fine if exists in table already):
{'genres': ['object genre=mystery not exist.']}
i thought should work using object.get_or_create() in create() method of movieserializer doesn't seem work.
also i'm sending data post request in format:
{'tmdb_id': 14, 'title': 'some movie', 'release_date': '2011-12-12', 'genres': ['action', 'mystery']}
not sure if matters.
here's code:
views.py
class createmovieview(generics.listcreateapiview): queryset = movie.objects.all() serializer_class = movieserializer def perform_create(self, serializer): """save post data when creating new movie.""" serializer.save() class moviedetailsview(generics.retrieveupdatedestroyapiview): queryset = movie.objects.all() serializer_class = movieserializer
models.py
class genre(models.model): genre = models.charfield(max_length=65) def __str__(self): return "{}".format(self.genre) class movie(models.model): tmdb_id = models.integerfield(primary_key=true) title = models.charfield(max_length=255) release_date = models.datefield() imdb_id = models.charfield(max_length=255, blank=true) img_path = models.charfield(max_length=255, blank=true) runtime = models.charfield(max_length=65, blank=true) synopsis = models.textfield(blank=true) imdb_rating = models.decimalfield(max_digits=3, decimal_places=1, blank=true, null=true) metascore = models.integerfield(blank=true, null=true) genres = models.manytomanyfield(genre, related_name='genres', blank=true) def __str__(self): return "{}".format(self.title)
serializers.py
class movieserializer(serializers.modelserializer): """serializer map model instance json format.""" genres = serializers.slugrelatedfield(slug_field='genre', many=true, queryset=genre.objects.all()) class meta: """meta class map serializer's fields model fields.""" model = movie fields = ('tmdb_id', 'imdb_id', 'title', 'release_date', 'img_path', 'runtime', 'synopsis', 'imdb_rating', 'metascore', 'genres') def create(self, validated_data): genres_data = validated_data.pop('genres') movie = movie.objects.create(**validated_data) genre_name in genres_data: genre, created = genre.objects.get_or_create(genre=genre_name) movie.genres.add(genre) return movie
i'm not sure why error get, seems your'e not using views correctly allow creation of movie instances. listcreateapiview lets create lists of movies should, instead, add createmodelmixin other view:
class moviedetailsview(generics.retrieveupdatedestroyapiview, mixins.createmodelmixin): queryset = movie.objects.all() serializer_class = movieserializer
or, better, use modelviewset:
from restframework import viewsets class movieviewset(viewsets.modelviewset): queryset = ...
Comments
Post a Comment