📜  CharField – Django 模型

📅  最后修改于: 2022-05-13 01:55:44.928000             🧑  作者: Mango

CharField – Django 模型

CharField 是一个字符串字段,用于小到大的字符串。它就像 C/C++ 中的字符串字段。 CharField 通常用于存储小字符串,如名字、姓氏等。要存储较大的文本,则使用 TextField。此字段的默认表单小部件是 TextInput。

CharField 有一个额外的必需参数:

CharField.max_length

字段的最大长度(以字符为单位)。 max_length 在数据库级别和 Django 使用 MaxLengthValidator 的验证中强制执行。

句法:

field_name = models.CharField(max_length=200, **options) 

Django Model CharField 解释

使用示例说明 CharField。考虑一个名为 geeksforgeeks 的项目,它有一个名为 geeks 的应用程序。

极客应用的models.py文件中输入以下代码。

Python3
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)


Python3
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]


Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00
 
from django.db import migrations, models
 
class Migration(migrations.Migration):
 
    initial = True
 
    dependencies = [
    ]
 
    operations = [
        migrations.CreateModel(
            name ='GeeksModel',
            fields =[
                ('id',
                  models.AutoField(
                  auto_created = True,
                  primary_key = True,
                  serialize = False,
                  verbose_name ='ID'
                )),
                ('geeks_field',
                  models.CharField(
                  max_length = 200,
                )),
            ],
        ),
    ]


Python3
# importing the model
# from geeks app
from geeks.models import GeeksModel
 
# creating a instance of
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field ="GFG is Best")
geek_object.save()


将极客应用添加到 INSTALLED_APPS

Python3

# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]

现在,当我们从终端运行 makemigrations 命令时,

Python manage.py makemigrations

将在 geeks 目录中创建一个名为 migrations 的新文件夹,其中包含一个名为 0001_initial.py 的文件

Python3

# Generated by Django 2.2.5 on 2019-09-25 06:00
 
from django.db import migrations, models
 
class Migration(migrations.Migration):
 
    initial = True
 
    dependencies = [
    ]
 
    operations = [
        migrations.CreateModel(
            name ='GeeksModel',
            fields =[
                ('id',
                  models.AutoField(
                  auto_created = True,
                  primary_key = True,
                  serialize = False,
                  verbose_name ='ID'
                )),
                ('geeks_field',
                  models.CharField(
                  max_length = 200,
                )),
            ],
        ),
    ]

现在运行,

Python manage.py migrate

因此,当您在项目上运行迁移时,会创建一个 geeks_field CharField 。它是一个存储从小到大的字符串的字段。

如何使用字符域?

CharField 用于在数据库中存储小字符串。可以存储名字、姓氏、地址详细信息等。应该给 CharField 一个参数 max_length 以指定它需要存储的字符串的最大长度。在生产服务器中,部署 Django 应用程序后,空间非常有限。因此,根据字段的要求使用 max_length 始终是最佳的。让我们创建一个我们创建的 CharField 的实例并检查它是否工作。

Python3

# importing the model
# from geeks app
from geeks.models import GeeksModel
 
# creating a instance of
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field ="GFG is Best")
geek_object.save()

现在让我们在管理服务器中检查它。我们已经创建了 GeeksModel 的一个实例。

CharField django 模型

字段选项

字段选项是赋予每个字段的参数,用于应用某些约束或将特定特征赋予特定字段。例如,向 CharField 添加参数 null = True 将使其能够将该表的空值存储在关系数据库中。
以下是 CharField 可以使用的字段选项和属性。

Field OptionsDescription
NullIf True, Django will store empty values as NULL in the database. Default is False.
BlankIf True, the field is allowed to be blank. Default is False.
db_columnThe name of the database column to use for this field. If this isn’t given, Django will use the field’s name. 
 
db_indexIf True, a database index will be created for this field
db_tablespaceThe name of the database tablespace to use for this field’s index, if this field is indexed. The default is the project’s DEFAULT_INDEX_TABLESPACE setting, if set, or the db_tablespace of the model, if any. If the backend doesn’t support tablespaces for indexes, this option is ignored.
DefaultThe 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_textExtra “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_keyIf True, this field is the primary key for the model.
editableIf 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_messagesThe 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_textExtra “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_nameA 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. 
 
validatorsA list of validators to run for this field. See the validators documentation for more information. 
 
UniqueIf True, this field must be unique throughout the table.