如何在UserDetialsSerializer中定义userprofile?

时间:2015-09-13 13:47:45

标签: django django-rest-framework user-profile django-serializer

我希望能够通过以下方式访问userprofile个实例:
profile = instance.userprofile

中的UserSerializer声明

instance通过以下方式创建:
instance = super(UserSerializer, self).update(instance, validated_data)声明 UserSerializer

由于UserSerializer继承了UserDetailsSerializer,我想我应该在userprofile中定义UserDetailsSerializer
但我不知道怎么做?

问题:如何在userprofile中定义UserDetailsSerializer以实现上述目标?

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

UserDetailsS​​erializer:

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

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

UserProfile 型号:

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

请问是否需要更清晰?

2 个答案:

答案 0 :(得分:0)

认为你想让序列化器方法字段成为序列化器的一部分吗? (我不完全理解你的问题);

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',)

答案 1 :(得分:0)

我想我已经回答了类似的here

documentation中,假设已经创建了userprofile,现在可以更新。你只需要一张支票

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