gpt4 book ai didi

python - Django PositiveIntegerField 接受否定

转载 作者:太空宇宙 更新时间:2023-11-03 12:59:05 24 4
gpt4 key购买 nike

我的 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") 测试它,以防它是一个字符串格式错误,我得到了很多。

catavaran 的回答包括:

post.full_clean()

也失败了。

最佳答案

这是 validating objects 的摘录文档章节:

Note that full_clean() will not be called automatically when you call your model’s save() method. You’ll need to call it manually when you want to run one-step model validation for your own manually created models.

所以验证和保存模型应该是这样的:

post = Post(author=test_user_profile, title='Django Testing',
content='hello world', views=-10)
post.full_clean()
post.save()

更新: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com