how to define a userprofile into UserDetialsSerializer?

女生的网名这么多〃 提交于 2020-01-07 01:48:57

问题


I want to be able to access a userprofile instance through :
profile = instance.userprofile statement in UserSerializer

instance is created through:
instance = super(UserSerializer, self).update(instance, validated_data) statement in UserSerializer

Since UserSerializer is inheriting UserDetailsSerializer, i think i should define a userprofile in UserDetailsSerializer.
But i dont know how to do it ?

Question: How to define userprofile in UserDetailsSerializer to achieve the above ?

UserSerializer:

class UserSerializer(UserDetailsSerializer):
    company_name = serializers.CharField(source="userprofile.company_name")

    class Meta(UserDetailsSerializer.Meta):
        fields = UserDetailsSerializer.Meta.fields + ('company_name',)  

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('userprofile', {})
        company_name = profile_data.get('company_name')

        instance = super(UserSerializer, self).update(instance, validated_data)

        # get and update user profile
        profile = instance.userprofile
        if profile_data and company_name:
            profile.company_name = company_name
            profile.save()
        return instance

UserDetailsSerializer:

class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()

        fields = ('username','email', 'first_name', 'last_name')
        read_only_fields = ('email', )

UserProfile model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    # custom fields for user
    company_name = models.CharField(max_length=100)

Do ask if more clarity is required?


回答1:


I think you want a serializer methodfield to be part of your serializer? (I don't full understand your question);

class UserDetailsSerializer(serializers.ModelSerializer):
    user_related = serializers.Field(source='method_on_userprofile')
    class Meta:
        model = UserProfile
        fields = ('username','email', 'first_name', 'user_related', )
        read_only_fields = ('email', 'user_related',)



回答2:


I think I have answered similar one here

In the documentation it is assumed that userprofile was already created and now can be updated. You just need a check

# get and update user profile
    try:
        profile = instance.userprofile
    except UserProfile.DoesNotExist:
        profile = UserProfile()
    if profile_data and company_name:


来源:https://stackoverflow.com/questions/32550317/how-to-define-a-userprofile-into-userdetialsserializer

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