unique=True – Django 内置字段验证
Django 模型中的内置字段验证是为所有 Django 字段预定义的验证。每个字段都带有来自 Django 验证器的内置验证。还可以添加更多内置字段验证,以在特定字段上应用或删除某些约束。 unique=True 将字段设置为唯一,即一旦在字段中输入值,就不能以任何方式在该模型的任何其他实例中输入相同的值。它通常用于像 Roll Number、Employee Id 等应该是唯一的字段。
句法
field_name = models.Field(unique=True)
Django 内置字段验证unique=True
解释
使用示例说明唯一性。考虑一个名为geeks
的项目,它有一个名为geeksforgeeks
的应用程序。
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
在极客应用的models.py
文件中输入以下代码。我们将使用 CharField 来试验所有字段选项。
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.CharField(
max_length = 200,
unique = True
)
在 Django 上运行 makemigrations 和 migrate 并渲染上述模型后,让我们从 Django 管理界面创建一个带有字符串“ a ”的实例。现在为了展示unique=True的约束,让我们尝试使用相同的字符串再创建一个模型实例。现在它将显示此错误。
独特的先进理念
这是在数据库级别和模型验证中强制执行的。如果您尝试在唯一字段中保存具有重复值的模型,模型的save()方法将引发django.db.IntegrityError 。此选项对除 ManyToManyField 和 OneToOneField 之外的所有字段类型均有效。
请注意,当 unique 为 True 时,您不需要指定db_index ,因为 unique 意味着创建索引。
更多内置字段验证
Field Options | Description |
---|---|
Null | If True, Django will store empty values as NULL in the database. Default is False. |
Blank | If True, the field is allowed to be blank. Default is False. |
db_column | The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. |
Default | The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
primary_key | If True, this field is the primary key for the model. |
editable | If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. |
error_messages | The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
verbose_name | A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. |
validators | A list of validators to run for this field. See the validators documentation for more information. |
Unique | If True, this field must be unique throughout the table. |