我正在尝试更新包含布尔值的Django模型字段。这里有一个用户将申请项目,默认情况下,一个字段将自动为false。在检查了此插入之后,系统的管理将使该字段为真并批准提案。所以,现在我想将该字段更新为“ True”
def project(request, project_id):
all_primary_info = ProjectPrimaryInfo.objects.get(pk=project_id)
if all_primary_info.approval == 'False':
all_primary_info.approval.update(True)
return render(request, 'administration/all_project_status.html')
这是ProjectPrimaryInfo模型:
class ProjectPrimaryInfo(models.Model):
id = models.AutoField(primary_key=True)
s_id = models.ForeignKey(Student, null=True, blank=True, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
approval = models.BooleanField(default=False)
p_type = models.CharField(max_length=20) # project or thesis
p_name = models.CharField(max_length=50)
p_description = models.CharField(max_length=500)
vision = models.CharField(max_length=500)
charter = models.CharField(max_length=250)
def __str__(self):
return self.p_name
我希望all_primary_info.approval为“ true”
答案 0 :(得分:1)
问题在于您对此行的看法
if all_primary_info.approval == 'False':
在模型中,您将approval
定义为布尔字段,但在上一行中,您使用了'False'
,它是一个String而不是NOT Bool,因为您将其用单个反逗号括起来。实际上,您是在问Django
if <Boolean Value> == <String Value>
始终为假,因此不会执行if
条件下的代码。要解决此问题,您需要删除False
前后的逗号。因此,您上面的代码行应该是
if all_primary_info.approval is False:
# Do your stuff like this
# all_primary_info.approval(True) is not correct.
# You can simply perform a .save on model instance to update the value
all_primary_info.approval = True
all_primary_info.save()
希望这可以解决您的问题。