gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:56 27 4
gpt4 key购买 nike

我正在使用 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>]>

我的问题是为什么 Person 等级属性可以创建“另一个”,因为我知道等级模型的最大长度为 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/

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