我正在尝试在应用程序中启用部分更新功能。我扩展了 django auth 用户模型以允许一些额外的用户数据;当我向 View 发送 PATCH 请求(扩展rest_framework.generics.RetrieveUpdateAPIView
)时,会收到正确的数据,但它似乎忽略了嵌套数据。示例:
{'id': 1, 'foo': 'bar', 'baz': 'qux', 'user': {'username': 'user1', 'first_name': 'User', 'last_name': 'One'}}
foo
和 baz
已正确更新,但 username
、first_name
和 last_name
全部被忽略。
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name')
class UsersSerializer(serializers.ModelSerializer):
user = UserProfileSerializer(many=False, read_only=False, partial=True)
class Meta:
model = Users
fields = ('id', 'foo', 'baz', 'yin', 'yang', 'user')
depth = 1
class UserProfileGenericAPIView(generics.GenericAPIView):
serializer_class = UsersSerializer
queryset = Users.objects.all()
def pre_save(self, obj):
pass
class UserProfileView(UserinfoGenericAPIView, generics.RetrieveUpdateAPIView):
pass
有人可以告诉我部分更新是否支持深度,如果是的话,我可能做错了什么?
最佳答案
这最初是在问题中回答的,但我觉得它值得一个像样的解释。
在 Django REST Framework 3 中,保存嵌套数据的过程已经变得更加清晰。现在,您可以覆盖序列化器上的 update
并操作 validated_data
,手动更新模型对象。这是specifically documented now ,但实现通常是针对具体情况的。
原始答案(在问题中)由 user2708386
Short answer is yes, it's possible. The problem was that I still needed to override the
.save()
method on my model to also save the related User object.
class Users(models.Model):
user = models.OneToOneField(User)
foo = models.CharField()
baz = models.CharField()
yin = models.CharField()
yang = models.CharField()
def save(self, *args, **kwargs):
user_ = self.user
user_.save(update_fields=('username', 'first_name', 'last_name'), **kwargs)
return super(Users, self).save(*args, **kwargs)
关于python - Django REST Framework 部分深度更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452635/