django 对象中的保存方法不保存布尔模型字段,它被传递为 false
save method in django object not saving boolean model field it it is passed false
我有这个型号:
class Comment(models.Model):
comment_text = models.TextField("Comentário")
user = models.ForeignKey(Profile)
created = models.DateTimeField(auto_now_add=True, verbose_name="Criação")
updated = models.DateTimeField(auto_now=True, verbose_name="Última modificação")
confidential = models.BooleanField("Confidencial", default=False)
我有这个视图集(使用休息框架):
@detail_route(methods=['POST'], permission_classes= [IsOwnerOrReadOnly])
def set_confidential(self, request, pk=None):
comment = self.get_object()
if(request.data.get("booleanField", None) != None):
comment.confidential = request.data["booleanField"];
comment.save()
return Response({'from':'set_confidential','status':_("Confidential status changed")})
else:
return Response({"status":status.HTTP_400_BAD_REQUEST})
问题是,当我将 "False" 值传递给该视图时,我的对象已更新,但字段 "confidential" 仍然为真(假设它像以前那样)。为什么会这样?
您应该保存 comment
对象。请注意,在布尔上下文中,任何非空字符串都被视为 True
:
comment.confidential = (request.data["booleanField"].lower() == 'true')
comment.save()
我有这个型号:
class Comment(models.Model):
comment_text = models.TextField("Comentário")
user = models.ForeignKey(Profile)
created = models.DateTimeField(auto_now_add=True, verbose_name="Criação")
updated = models.DateTimeField(auto_now=True, verbose_name="Última modificação")
confidential = models.BooleanField("Confidencial", default=False)
我有这个视图集(使用休息框架):
@detail_route(methods=['POST'], permission_classes= [IsOwnerOrReadOnly])
def set_confidential(self, request, pk=None):
comment = self.get_object()
if(request.data.get("booleanField", None) != None):
comment.confidential = request.data["booleanField"];
comment.save()
return Response({'from':'set_confidential','status':_("Confidential status changed")})
else:
return Response({"status":status.HTTP_400_BAD_REQUEST})
问题是,当我将 "False" 值传递给该视图时,我的对象已更新,但字段 "confidential" 仍然为真(假设它像以前那样)。为什么会这样?
您应该保存 comment
对象。请注意,在布尔上下文中,任何非空字符串都被视为 True
:
comment.confidential = (request.data["booleanField"].lower() == 'true')
comment.save()