Instead of Primary Key Send Different Field in Django REST Framework

前端 未结 5 1020
萌比男神i
萌比男神i 2020-12-30 07:27

serializers.py

class MovieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Movie
        fields = [
            \'popular         


        
5条回答
  •  醉梦人生
    2020-12-30 08:00

    Override the create() method of the serializer as below,

    class MovieSerializer(serializers.ModelSerializer):
        genre = serializers.ListSerializer(child=serializers.CharField())
    
        class Meta:
            model = Movie
            fields = [
                'popularity',
                'director',
                'genre',
                'imdb_score',
                'name',
            ]
    
        def create(self, validated_data):
            genre = validated_data.pop('genre',[])
            movie = super().create(validated_data)
            genre_qs = Genre.objects.filter(name__in=genre)
            movie.genre.add(*genre_qs)
            return movie

提交回复
热议问题