0

我希望能夠通過訪問userprofile實例:
profile = instance.userprofile聲明UserSerializer如何在UserDetialsSerializer中定義一個userprofile?

instance創建通過:
instance = super(UserSerializer, self).update(instance, validated_data)聲明 UserSerializer

由於UserSerializer在繼承UserDetailsSerializer,我想我應該在UserDetailsSerializer中定義userprofile
但我不知道該怎麼做?

問題:如何定義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',) 

用戶配置型號:

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

請問是否需要更清晰?

回答

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

我想我已經回答了類似的一個here

documentation假設USERPROFILE已經創建,現在可以進行更新。您只需要支票

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