默认 - Django 内置字段验证
Django 模型中的内置字段验证是为所有 Django 字段预定义的验证。每个字段都带有来自 Django 验证器的内置验证。还可以添加更多内置字段验证,以在特定字段上应用或删除某些约束。 default=value
将使该字段默认为value 。无需显式定义任何值,即使未输入字段,它也会默认为value 。值取决于字段本身,就像字段是日期字段一样,它将仅接受具有预定义验证的日期值。
句法
field_name = models.Field(default = value)
Django 内置字段验证null=True
解释
使用示例说明default=value 。考虑一个名为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, default = "GFG is best")
在 Django 上运行 makemigrations 和 migrate 并渲染上述模型后,让我们尝试使用 Django shell 中的 None 创建一个实例。要启动 Django shell,请输入命令,
Python manage.py shell
现在让我们尝试使用None创建 GeeksModel 的实例。
# importing required model
from geeks.models import GeeksModel
# creating instance of GeeksModel
# without entering anything
s = GeeksModel.objects.create()
# saving current model instance
s.save()
让我们检查管理界面是否创建了模型实例。
因此,default=value 修改字段以设置特定字段的默认值。
默认的高级概念
在 BooleanField 中,如果要默认启用或禁用该字段,可以同时使用default=True和default=false轻松完成。
更多内置字段验证
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. |
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。