我希望能够通过以下方式访问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
UserDetailsSerializer:
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)
请问是否需要更清晰?
答案 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: