django-rest-framework serializer different fields in multiple views

前端 未结 3 747
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 02:41

I am new at Django and couldn\'t find solution for my problem.

The problem is to force specific serializer for include different amount of fields in case of utilizing di

3条回答
  •  情深已故
    2021-02-08 03:17

    class DynamicFieldsModelSerializer(ModelSerializer):
        """
        A ModelSerializer that takes an additional `fields` and 'exclude' argument that
        controls which fields should be displayed.
        """
    
        def __init__(self, *args, **kwargs):
            # Don't pass the 'fields' arg up to the superclass
            fields = kwargs.pop('fields', None)
            exclude = kwargs.pop('exclude', None)
    
            # Instantiate the superclass normally
            super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
    
            if fields is not None:
                # Drop any fields that are not specified in the `fields` argument.
                allowed = set(fields)
                existing = set(self.fields.keys())
                for field_name in existing - allowed:
                    self.fields.pop(field_name)
    
            if exclude is not None:
                not_allowed = set(exclude)
                for exclude_name in not_allowed:
                    self.fields.pop(exclude_name)
    
    
    
    class UserCreateSerializer(DynamicFieldsModelSerializer):
        class Meta:
            model = User
            fields = ('username', 'tel', 'email', 'password')
    

    use:

    serializer = UserCreateSerializer(data=request.data, fields=('username', 'password', 'tel'))
    

    or

    serializer = UserCreateSerializer(data=request.data, fields=('username', 'password', 'email'))
    

提交回复
热议问题