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

后端 未结 5 2475
半阙折子戏
半阙折子戏 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 08:51

    IMHO, multiple serializers are only going to create more and more confusion.

    Rather I would prefer below solution:

    1. Don't change your viewset (leave it default)
    2. Add .validate() method in your serializer; along with other required .create or .update() etc. Here, real logic will go in validate() method. Where based on request type we will be creating validated_data dict as required by our serializer.

    I think this is the cleanest approach.

    See my similar problem and solution at DRF: Allow all fields in GET request but restrict POST to just one field

提交回复
热议问题