Instead of Primary Key Send Different Field in Django REST Framework

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

serializers.py

class MovieSerializer(serializers.ModelSerializer):

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


        
5条回答
  •  一整个雨季
    2020-12-30 07:42

    On solution is to override genre field in your serializer, to accept a list of strings like this:

    class MovieSerializer(serializers.ModelSerializer):
    
        genre = serializer.ListField(child=serializers.CharField())
    
        class Meta:
            model = Movie
            fields = [
                'popularity',
                'director',
                'genre',
                'imdb_score',
                'name',
            ]  
        def validate(self, data):
            genre = data.get('genre', [])
            genre_obj_list = [Genre.objects.get(name=name) for name in genre.all()]
            data.update({'genre': genre_obj_list})
            return data
    

    And on validate method try to fetch each object by their names and put in a new list and update data result with new list of objects. (I know it's not the cleanest solutions, but it works fine)

    you could also try to use MethodSerializer or define a GenreSerializer and fetch objects in that by their names and use that in the parent serializer as an input.

提交回复
热议问题