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

后端 未结 5 2421
半阙折子戏
半阙折子戏 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

    I know it's a little late, but just in case someone else needs it. There are some third party packages for drf that allow dynamic setting of included serializer fields via the request query parameters (listed in the official docs: https://www.django-rest-framework.org/api-guide/serializers/#third-party-packages).

    IMO the most complete ones are:

    1. https://github.com/AltSchool/dynamic-rest
    2. https://github.com/rsinger86/drf-flex-fields

    where (1) has more features than (2) (maybe too many, depending on what you want to do).

    With (2) you can do things such as (extracted from the repo's readme):

    class CountrySerializer(FlexFieldsModelSerializer):
        class Meta:
            model = Country
            fields = ['name', 'population']
    
    
    class PersonSerializer(FlexFieldsModelSerializer):
        country = serializers.PrimaryKeyRelatedField(read_only=True)
    
        class Meta:
            model = Person
            fields = ['id', 'name', 'country', 'occupation']
    
        expandable_fields = {
            'country': (CountrySerializer, {'source': 'country', 'fields': ['name']})
        }
    

    The default response:

    {
      "id" : 13322,
      "name" : "John Doe",
      "country" : 12,
      "occupation" : "Programmer"
    }
    

    When you do a GET /person/13322?expand=country, the response will change to:

    {
      "id" : 13322,
      "name" : "John Doe",
      "country" : {
        "name" : "United States"
      },
      "occupation" : "Programmer",
    }
    

    Notice how population was ommitted from the nested country object. This is because fields was set to ['name'] when passed to the embedded CountrySerializer.

    This way you can keep your POST requests including just an id, and "expand" GET responses to include more details.

提交回复
热议问题