我有一个个人资料模型,用户注册后必须更新他们的个人资料。为此我设计了两个序列化程序,一个UserSerializer显示用户列表,另一个ProfileSerializer有很多字段供用户添加到他们的个人资料中。用户不仅可以更新他们的个人资料,如身高,体重,年龄,位置,身体类型等,还应该从个人资料中更新first_name,last_name和email。
这是我的UserSerializer和ProfileSerializer
class ProfileSerializer(serializers.ModelSerializer):
# url = serializers.HyperlinkedRelatedField(source="user", view_name="user_profile")
user = serializers.PrimaryKeyRelatedField(read_only=True)
token = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Profile
fields = ('token', 'user', 'current_location', 'permanent_location', 'dob',
'about_me', 'gender_status', 'create_profile_for', 'marital_status',
'height', 'weight', 'body_type', 'complexion',)
def update(self, instance, validated_data):
first_name = validated_data.pop('first_name', None)
last_name = validated_data.pop('last_name', None)
user_inst_fields = {}
if first_name:
user_inst_fields['first_name'] = first_name
if last_name:
user_inst_fields['last_name'] = last_name
if user_inst_fields:
User.objects.update_or_create(id=instance.user.id, defaults=user_inst_fields)
profile, created = Profile.objects.update_or_create(token=instance.token, defaults=validated_data)
print('profile', profile, created)
return profile
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(required=True)
class Meta:
model = User
fields = ('id', 'profile', 'username', 'email', 'first_name', 'last_name',)
我无法显示first_name,last_name和username的字段,以便用户更新它们及其个人资料。
您可以看到屏幕截图,没有显示first_name,last_name和用户名
答案 0 :(得分:1)
您在first_name
中使用last_name
关键字参数在username
中显示ProfileSerializer
,source
和CharField
以及first_name和用户名
class ProfileSerializer(serializers.ModelSerializer):
# url = serializers.HyperlinkedRelatedField(source="user", view_name="user_profile")
user = serializers.PrimaryKeyRelatedField(read_only=True)
token = serializers.PrimaryKeyRelatedField(read_only=True)
first_name = serializers.CharField(source = "user.first_name")
last_name = serializers.CharField(source = "user.last_name")
username = serializers.CharField(source = "user.username")
class Meta:
model = Profile
fields = ('token', 'user', 'current_location', 'permanent_location', 'dob',
'about_me', 'gender_status', 'create_profile_for', 'marital_status',
'height', 'weight', 'body_type', 'complexion',)
def update(self, instance, validated_data):
first_name = validated_data.pop('first_name', None)
last_name = validated_data.pop('last_name', None)
user_inst_fields = {}
if first_name:
user_inst_fields['first_name'] = first_name
if last_name:
user_inst_fields['last_name'] = last_name
if user_inst_fields:
User.objects.update_or_create(id=instance.user.id, defaults=user_inst_fields)
profile, created = Profile.objects.update_or_create(token=instance.token, defaults=validated_data)
print('profile', profile, created)
return profile
现在,DRF将从个人资料模型的first_name
关系中提取last_name
,email
和user
。