gpt4 book ai didi

django - 使用 Django 序列化程序的 PUT 请求

转载 作者:行者123 更新时间:2023-12-04 00:17:33 24 4
gpt4 key购买 nike

我有一种架构,当用户注册时,他/她的设置会被初始化。所以我们需要 GET 和 PUT 来分别获取或更新设置 API 上的设置。

我正在使用 django rest 框架的模型序列化器来存储和获取设置。它在给出响应方面效果很好,但不能将其保存到模型中。

serializers.py

class UserSettingsSerializer(serializers.ModelSerializer):

class Meta:
model = UserSettings
fields = ('group_notifications', 'updates', 'goal_remind_me',
'goal_days', 'goal_time_interval', 'user')

models.py
class UserSettings(models.Model):

class Meta:
db_table = 'user_settings'

user = models.ForeignKey('User')
group_notifications = models.BooleanField(default=True)
updates = models.BooleanField(default=False)
goal_remind_me = models.BooleanField(default=False)
goal_days = ListField()
goal_time_interval = models.IntegerField(null=True)

views.py
def settings(request, pk):
if request.method == 'PUT':
request.data['user'] = user.id

serializer = UserSettingsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
serializer_dict = serializer.data
serializer_dict["message"] = "Settings updated successfully."
return Response(serializer_dict, status=status.HTTP_200_OK)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

我得到了预期的响应,但它没有在 user_settings 中存储数据表,我正在使用 PostgreSql。

最佳答案

为了让 ModelSerializer 执行更新,您需要将要更新的实例传递给构造函数。

def settings(request, pk):
# query for the UserSettings object
instance = get_object_or_404(UserSettings.objects.all(), pk=pk)

if request.method == 'PUT':
request.data['user'] = user.id

# pass in the instance we want to update
serializer = UserSettingsSerializer(instance, data=request.data)

# validate and update
if serializer.is_valid():
serializer.save()
serializer_dict = serializer.data
serializer_dict["message"] = "Settings updated successfully."
return Response(serializer_dict, status=status.HTTP_200_OK)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

关于django - 使用 Django 序列化程序的 PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32064626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com