简体   繁体   中英

DRF: a way to use default UserProfile field in serializer?

Using current User model in your serializers is easy:

user = serializers.PrimaryKeyRelatedField(
        read_only=True,
        default=serializers.CurrentUserDefault()
    )

but what if I have my own UserProfile model and I want to use current UserProfile in a serializer.

Just doing CurrentUserDefault().profile does not work, of course because at this point this is an empty object.

It turns out this problem is very easily solved. If you look at the source code of CurrentUserDefault class, you will see it is very simple:

class CurrentUserDefault(object):
    def set_context(self, serializer_field):
        self.user = serializer_field.context['request'].user

    def __call__(self):
        return self.user

    def __repr__(self):
        return unicode_to_repr('%s()' % self.__class__.__name__)

I guess set_context is called by Serializer , and then __call__ method called to recieve the object. So it is very simple to rewrite this code in any way you want.

TLDR

Just add this somewhere:

class CurrentUserProfileDefault(serializers.CurrentUserDefault):
    def __call__(self):
        return self.user.userprofile

And where ever you need your profile just write:

user_profile = serializers.PrimaryKeyRelatedField(
        read_only=True,
        default=serializers.CurrentUserProfileDefault()
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM