Django REST Framework CurrentUserDefault() with serializer

戏子无情 提交于 2019-11-28 00:16:47

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'
        )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!