这里我正在尝试更新用户和user_profile模型。这将更新用户,但与此有关的一个问题是:如果我不提供地址或任何其他字段,那么更新后它将变为空白。如何解决此问题?
还没有在更新表单中预先填充用户数据。在更新表单中,是否不应该已经存在用户数据?
models.py
class Profile(models.Model):
user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,related_name='profile')
address = models.CharField(max_length=250,blank=True,null=True)
serializer.py
class UpdateUserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = get_user_model()
fields = ['first_name', 'last_name', 'profile']
def update(self, instance, validated_data):
instance.username = validated_data.get('username', instance.username)
instance.email = validated_data.get('email', instance.email)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.save()
profile_data = validated_data.pop('profile')
instance.profile.address = profile_data.get('address', instance.profile.address)
instance.profile.save()
return instance
views.py
class UpdateUser(generics.UpdateAPIView):
serializer_class = UpdateUserSerializer
queryset = get_user_model().objects.all()
您可以在update
方法上检查参数,如果ViewSet中不存在则抛出错误: