如何在Django模型上更新布尔字段?

时间:2019-09-02 08:33:05

标签: python django

我实现了一个视图,该视图应该更新Django模型上的两个布尔字段,即is_published和Submitted。但是,当前,该视图仅能够更新第一个布尔字段(is_published),而忽略第二个布尔字段(submitted)。我在做什么错?我该如何实施同时更新两个字段的解决方案?

这是我的代码

型号

class Course(models.Model):

    is_published = models.BooleanField(default=False)

    submitted = models.BooleanField(default=False)

查看

class UpdateVideoAPIPublishView(generics.UpdateAPIView):
    """ Update course """

    permission_classes = (IsAuthenticated,)
    renderer_classes = (CourseJSONRenderer,)
    serializer_class = CourseSerializer

    def update(self, request, *args, **kwargs):
        course = get_object_or_404(
                Course, slug=self.kwargs['slug'])

        if not course.is_published:
            course.is_published = True
            course.submitted = False
            course.save()
            return Response(
                {"message": "Course updated succesfully"}, status=status.HTTP_201_CREATED)
        raise serializers.ValidationError(
            'Course already published'
        )

1 个答案:

答案 0 :(得分:0)

您可以尝试这样:

if not course.is_published:
      course.is_published = True
      course.save()
 if not course.submitted:
      course.submitted = True
      course.save()

正如@brunodesthuilliers在评论中所说,您也可以这样做:

if not course.is_published and not course.submitted:
          course.is_published = True
          course.submitted = True
          course.save()