的限制主要是針對表單驗證;只有很少的限制(主要是那些可能導致數據庫問題的限制),這些限制在您使用API時實施。
您可以輕鬆創建一個空的用戶(沒有用戶名的用戶):
>>> from django.contrib.auth.models import User
>>> u = User()
>>> u.save()
>>> u
<User: >
>>> u.id
2
但是,如果您嘗試創建空的用戶,你會得到一個IntegrityError
:
>>> u = User()
>>> u.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/models/base.py", line 553, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/models/query.py", line 1436, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 791, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/Users/burhan/work/projects/foo/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 234, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: column username is not unique
如果你看看模型,你會看到username
字段有一個db級限制(unique=True
):
`username = models.CharField(_('username'), max_length=30, unique=True...`
這在API級別強制執行,所以你不能有兩個用戶使用相同的username
領域。
的另一個例子是選擇參數。這主要用於演示。如果你有一個字段choices=('M','Male'),('F','Female')
;使用API,你可以插入任何單個字符,它會愉快地接受它。那些在數據庫級別執行
選項(這意味着,你無法從API 「違反」 他們)是:
unique
max_length
null
(不blank
混淆)
當我在django shell中鍵入這3行代碼時,它沒有錯誤地工作 – wong2