我在Django应用程序中有一个带有PositiveIntegerField的模型( View ):
class Post(models.Model):
author = models.ForeignKey('UserProfile')
creation_date = models.DateTimeField(auto_now_add=True)
views = models.PositiveIntegerField(default=0)
tags = models.ManyToManyField('Tag', through="PostTagging", null=False, blank=False)
rating = models.FloatField(default=0)
但是,当我测试它时,它接受负值:
测试:
def test_post_with_negative_views(self):
test_user = User.objects.get(username='test_student')
test_user_profile = UserProfile.objects.get(user=test_user)
post = Post.objects.create(author=test_user_profile, title='Django Testing', content='hello world', views=-10)
self.assertEquals(post.views, 0)
失败:
Creating test database for alias 'default' ...
......F.......
=====================================================================
FAIL: test_post_with_negative_views (bark.tets.PostTest)
---------------------------------------------------------------------
Traceback (most recent call last):
File "/home/ewan/Documents/WAD2/studeso/bark/bark/tests.py", line 58, in test_post_with_negative_views
self.assertEquals(post.views, 0)
AssertionError: -10 != 0
---------------------------------------------------------------------
FAILED (failures=1)
我在这里做错什么了吗?
我试过使用int(-10)和int(“-10”)进行测试,以防万一这是一个字符串格式化错误,我得到了很多。
双体船的答案包括:
post.full_clean()
也失败了。
最佳答案
这是文档的validating objects章的摘录:
因此,验证和保存模型应如下所示:
post = Post(author=test_user_profile, title='Django Testing',
content='hello world', views=-10)
post.full_clean()
post.save()
UPDATE :对于SQLite后端,似乎已关闭此验证。我在
django.db.backends.sqlite3.operations.DatabaseOperations
类中找到了此代码。def integer_field_range(self, internal_type):
# SQLite doesn't enforce any integer constraints
return (None, None)
此方法的值用于构建
PositiveIntegerField
的验证器。据我了解,这样做是出于兼容性方面的考虑。因此,如果要使用SQLite,则必须手动添加验证器:
from django.core.validators import MinValueValidator
class Post(models.Model):
...
views = models.PositiveIntegerField(default=0,
validators=[MinValueValidator(0)])
进行此修改后,
full_clean()
应该可以按预期工作。关于python - Django PositiveIntegerField接受负数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29067045/