使用Django序列化程序

时间:2015-08-18 06:00:13

标签: django postgresql django-rest-framework serializer

我有一种架构,当用户注册时,他/她的设置被初始化。因此,我们需要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。

1 个答案:

答案 0 :(得分:1)

为了让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)