Django REST Framework CurrentUserDefault() with serializer

前端 未结 1 586
天命终不由人
天命终不由人 2020-12-06 14:46

I have been trying for a while now to add an \'owner\' field to my models. I have looked at other questions but I still have had no luck. Ideally when a new note is created,

相关标签:
1条回答
  • 2020-12-06 14:53

    I have a clean routine for this kind of situations, that I'll explain. first of all, CurrentUserDefault is not doing something magical, it is just returning the user of the request that we previously gave to the serializer (generic views pass the request to the serializer by calling get_serializer, since you are using generics you are doing fine).

    but for our purpose, we'll write a new customized CurrentUserDefault, that it'll return the id of the user:

    class CurrentUserDefault(object):
        def set_context(self, serializer_field):
            self.user_id = serializer_field.context['request'].user.id
    
        def __call__(self):
            return self.user_id
    
        def __repr__(self):
            return unicode_to_repr('%s()' % self.__class__.__name__)
    

    now we are just gonna use this CurrentUserDefault and fill the owner_id field of the NoteSummarySerializer, I suggest you use serializers.HiddenField, cause according to the drf doc:

    A field class that does not take a value based on user input, but instead takes its value from a default value or callable.

    This field will be present in validated_data but will not be used in the serializer output representation.

    so it only gets its value from default or callable, so it's not Changeable by user input, and also it will not be used in the serializer output representation. seems great, right?

    we just add this field to the serializer:

    class NoteSummarySerializer(serializers.ModelSerializer):
        owner_id = serializers.HiddenField(default=CurrentUserDefault())
    
        class Meta:
            model = Note
            fields = (
                'pk',
                'title',
                'containerId',
                'created',
                'updated',
                'owner_id', ### dont forget to add it to the fields.
            )
    

    then for final step, since we used owner_id fo filling the the owner, the name owner is available for other uses. in this case i think make it CharField and give owner.username (or anything you want) to its source and make its readonly True, so our Serializer finnally gonna be like:

    class NoteSummarySerializer(serializers.ModelSerializer):
        owner_id = serializers.HiddenField(default=CurrentUserDefault())
        owner = serializers.CharField(source='owner.username', read_only=True)
    
        class Meta:
            model = Note
            fields = (
                'pk',
                'title',
                'containerId',
                'created',
                'updated',
                'owner_id',
                'owner'
            )
    
    0 讨论(0)
提交回复
热议问题