python - django 不检查objects.create 上的 CharField 长度

标签 python django sqlite django-models

我正在使用 django 1.10 并尝试制作一些模型,其中包括一些简单的选择,这是我的 models.py

@python_2_unicode_compatible
class Person(models.Model):
    Senior='A'
    Middle='B'
    Junior='C'
    class_person=[(Senior,'Senior'),(Middle,'Middle'),\
             (Junior,'Junior')]

    name=models.CharField(max_length=100)
    grade=models.CharField(max_length=2,choices=class_person,default=Junior)

    def __str__(self):
        return '%s in %s' % (self.name,self.grade)

    def is_senior(self):
        return self.grade in (self.Senior,self.Middle)

现在我尝试通过 shell 创建一些 Person 对象实例,例如

Person.objects.create(name='John',grade='Another')

现在我打电话

Person.objects.all()

它返回

<QuerySet [<Person: John in Another>]>

我的问题是,为什么“人员”等级属性可以创建“另一个”,因为我知道等级模型的最大长度为 2。谢谢您的解释

最佳答案

这就是 sqlite3 的工作原理。 Id 不强制长度限制

https://sqlite.org/faq.html#q9

SQLite does not enforce the length of a VARCHAR. You can declare a VARCHAR(10) and SQLite will be happy to store a 500-million character string there. And it will keep all 500-million characters intact. Your content is never truncated. SQLite understands the column type of "VARCHAR(N)" to be the same as "TEXT", regardless of the value of N.

如果您想要更多功能完整的数据库,请使用 postgres 或 mysql

关于python - django 不检查objects.create 上的 CharField 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40354401/

相关文章:

python - 使用 curve_fit 限制高斯拟合

python - 未绑定(bind)本地错误: local variable referenced before assignment when using list comprehension in python

django 获取关联数据一对一字段

python - key 错误 : 'HTTP_HOST' when running django tests

python - 根据用户选择模型表单中显示哪些字段

java - 结合 Realm 和 SQLite。?

android - Android(sqlite)中ListView中的删除查询和刷新

python - 在 Pyqt 的 qtable 中更改选定字符串的颜色

python - 如何从数据库中删除或编辑记录

python - 为什么 json.loads 关心使用哪种类型的引号?