What's the difference between CharField and TextField in Django?
Django is a back-end Python web framework that uses object-relational mapping (ORM), which adds an abstraction layer for users to interact with the database using Python classes. In the case of a relational database, each class represents a table. These Python classes are made inside models.py, the file in the app folder. Each class has its fields. For strings, we often use CharField or TextField. The CharField model field is used for small or medium-sized texts and allows us to specify the maximum length a string can have depending upon the limit allowed in that database. Unlike CharField, TextField has no limit to the number of characters a string can have.
The CharField model field
In Django, CharField is used for small to medium-sized texts with an optional argument of maximum string length.
Syntax
Here, the following code shows the general syntax of CharField:
Class CharField(max_length=None, **options)
Arguments
Two arguments can be given with CharField:
The
max_lengthargument limits the number of characters in a string at the database level. The DjangoMaxLengthValidatorchecks if any string exceeds the maximum string length specified by the user. This is done for all databases except PostgreSQL. Databases like MySQL allow a maximum of 255 characters in strings. Therefore, for any string with a non-zero length, themax_lengthshould be less than or equal to the maximum string size allowed in the database.Other optional arguments: Optional arguments include
null, which stores empty strings in the database. Collation, the string comparison and sorting rules for a specific database, is possible using thedb_collationargument.
One way to use Charfield is given below. The class, Employee_Data, inherits the models class and has one field called, employee_name.
from django.db import modelsclass Employee_Data(models.Model):employee_name = models.CharField(max_length = 100, db_collation = 'utf8_general_ci')
Code explanation
Line 1: Imports
modelmodule to define the database models in Django.Line 3: Defines the
Employee_Dataclass, which inherits from themodels.Modelbase class.Line 4: Defines the
employee_namestring, which stores theCharFieldstring field ofmax_lengthof100.
The TextField model field
The TextField model field is used for large-sized strings, such as long paragraphs. Unlike CharField, the maximum length for strings is not specified. The max_length optional argument, if given, is ignored at the database level.
Syntax
The following code shows the general syntax of TextField.
Class TextField(**options)
Arguments
All of the optional arguments that can be used with CharField can also be used with TextField. However, some arguments might not be relevant to a TextField, which are:
max_length: SinceTextFieldhandles large text, specifying a limit to the string length is not applicable. However, if the limit is given, it will be applied in theTextareawidget of the autogenerated form field.db_collation: Large text is not usually sorted or used for comparison because it is unstructured data. Therefore, this argument will also not apply toTextField.
The following code shows how to use TextField in Django.
from django.db import modelsclass Employee_Data(models.Model):employee_experience = models.TextField()
Code explanation
Line 1: Imports the
modelsmodule to define database models in Django.Line 3: Defines the
Employee_Dataclass, which inherits from themodels.Modelbase class.Line 4: Defines the string,
employee_experience, which stores theTextFieldstring with no additional arguments. However, as shown in the above table, all optional arguments can be used in the same way withTextFieldas they are used with theCharField.
The following table summarizes the key differences between the two model fields.
CharField | TextField |
Used for short to medium-sized strings | Used for large strings |
Usually requires a | Does not require a |
Used for strings like names, addresses, etc. | Used for strings like blogs, comments, etc. |
Strings using this field are suitable for searching, indexing, and sorting. | Strings using this field are not usually suitable for searching, indexing, or sorting. |
Syntax: | Syntax: |
Django application
The Django application below shows employee data for a firm. The models.py file shows the usage of both CharField and TextField. The name and designation fields are shorter strings, so we use CharField. However, the employees' bio, which stores their education and work experiences, is a larger string that requires TextField. The following command runs the Django application:
python manage.py runserver 0.0.0.0:8000
After pressing the “Run” button, type the above command in the terminal to start the application.
"""
Django settings for employee1 project.
Generated by 'django-admin startproject' using Django 4.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-q1@6djj(+530p#*f6$g!obp)-vrk23%3@i_z3l8rbgit_r(=88'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'employee_data',
'django_extensions',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'employee1.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["employee1/templates/"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'employee1.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Conclusion
The main difference between CharField and TextField is the size of the string stored in the database. A CharField stores small or medium-sized strings with a maximum limit specified for most databases. In contrast, a TextField is used for larger strings with no maximum limit.
Free Resources