Skip to main content
 首页 » 编程设计

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

2025年04月02日33java哥

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