Change a field in a Django REST Framework ModelSerializer based on the request type?

后端 未结 5 2430
半阙折子戏
半阙折子戏 2021-02-19 08:13

Consider this case where I have a Book and Author model.

serializers.py

class AuthorSerializer(serializers.ModelSerializer):

         


        
5条回答
  •  遥遥无期
    2021-02-19 09:10

    There is a feature of DRF where you can dynamically change the fields on the serializer http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

    My use case: use slug field on GET so we can see nice rep of a relation, but on POST/PUT switch back to the classic primary key update. Adjust your serializer to something like this:

    class FooSerializer(serializers.ModelSerializer):
        bar = serializers.SlugRelatedField(slug_field='baz', queryset=models.Bar.objects.all())
    
        class Meta:
            model = models.Foo
            fields = '__all__'
    
        def __init__(self, *args, **kwargs):
            super(FooSerializer, self).__init__(*args, **kwargs)
    
            try:
                if self.context['request'].method in ['POST', 'PUT']:
                    self.fields['bar'] = serializers.PrimaryKeyRelatedField(queryset=models.Bar.objects.all())
            except KeyError:
                pass
    

    The KeyError is sometimes thrown on code initialisation without a request, possibly unit tests.

    Enjoy and use responsibly.

提交回复
热议问题