我有一个带有布尔字段的模型:
@python_2_unicode_compatible
class Invoice(models.Model):
...
is_paid = models.BooleanField(default=False)
...
def __init__(self, *args, **kwargs):
super(Invoice, self).__init__(*args, **kwargs)
self.__tracked_fields = ['is_paid']
for field in self.__tracked_fields:
setattr(self, '__original_%s' % field, getattr(self, field))
我正在尝试在保存之前跟踪此字段中的更改:
def set_original_values(self):
for field in self.__tracked_fields:
original = '__original_%s' % field
original_value = getattr(self, original)
setattr(self, field, original_value)
return self.__dict__
def has_changed(self):
for field in self.__tracked_fields:
original = '__original_%s' % field
if getattr(self, original) != getattr(self, field):
return True
return False
def save(self, *args, **kwargs):
self.full_clean()
if self.has_changed():
if not self.can_be_confirmed():
self.set_original_values()
return super(Invoice, self).save(*args, **kwargs)
但是在测试时,我会得到具体的结果。
# THE FAILED TEST CODE
def test_has_no_changed(self):
self.invoice.amount = 1
self.invoice.is_paid = True
self.invoice.save()
print(self.invoice.is_paid)
print(type(self.invoice.is_paid))
self.assertFalse(self.invoice.is_paid)
部分测试结果:
.False
<class 'str'>
AssertionError: 'False' is not false
当然,如果我再次从数据库中获取一个对象,该字段中的值将转换为布尔值
但是在从数据库获取对象之前,测试只通过这种方式传递:
self.assertEqual(self.invoice.is_paid, 'False')
可能是什么问题?
**更新**
set_original_values
方法中的问题。
如果我这样做,如示例所示,则字段值类型为字符串。
P.S。感谢所有对我的问题都不利的人,因为它对解决我的问题非常有用......
答案 0 :(得分:0)
像这样工作:
自bool('False') == True
以来,我被迫分别检查'True'和'False'
def has_changed(self):
for field in self.__tracked_fields:
original = '__original_%s' % field
if getattr(self, original) is 'False':
return getattr(self, field) != False
elif getattr(self, original) is 'True':
return getattr(self, field) != True
else:
return getattr(self, original) != getattr(self, field)
这里完全一样。
def set_original_values(self):
values = {}
for field in self.__tracked_fields:
original = '__original_%s' % field
original_value = getattr(self, original)
if original_value is 'True':
setattr(self, field, True)
elif original_value is 'False':
setattr(self, field, False)
else:
setattr(self, field, original_value)
values[field] = getattr(self, field)
return values
现在测试成功了。