Django model fields define the type of data that can be stored in a database table. Each field in a Django model generally represents a column in the corresponding database table.
A model field is an attribute inside a Django model that defines what type of data should be stored.
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
Here, name and age are model fields.
Before defining fields, import Django's models module.
from django.db import models
The models module provides many built-in field types.
CharField is used for relatively short strings of text.
name = models.CharField(max_length=100)
Examples include:
name = models.CharField(max_length=100)
city = models.CharField(max_length=50)
course = models.CharField(max_length=100)
The max_length option specifies the maximum length of the value.
TextField is commonly used for larger amounts of text.
description = models.TextField()
It can be used for:
IntegerField is used for integer numbers.
age = models.IntegerField()
marks = models.IntegerField()
quantity = models.IntegerField()
It is useful when decimal values are not required.
PositiveIntegerField is intended for positive integer values and
zero.
quantity = models.PositiveIntegerField()
experience = models.PositiveIntegerField()
It can be useful for values such as quantities or years of experience where negative values are not appropriate.
DecimalField is useful for decimal values where precision matters,
such as fees and prices.
fee = models.DecimalField(
max_digits=10,
decimal_places=2
)
For example, a value such as 1500.50 can be represented using this
field configuration.
FloatField stores floating-point numbers.
rating = models.FloatField()
It can be useful for measurements or values where floating-point representation is appropriate.
BooleanField stores a true or false value.
is_active = models.BooleanField(default=True)
Examples:
is_paid = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
EmailField is designed for storing email addresses and provides
email validation behavior.
email = models.EmailField()
An optional maximum length can also be specified.
email = models.EmailField(max_length=254)
URLField is used for storing URLs.
website = models.URLField()
Example:
https://example.com
DateField stores date values without a time component.
birth_date = models.DateField()
admission_date = models.DateField()
It is useful for birthdays, admission dates, and other calendar dates.
DateTimeField stores both date and time.
created_at = models.DateTimeField()
A common option is auto_now_add=True for setting the field when an
object is first created.
created_at = models.DateTimeField(
auto_now_add=True
)
TimeField stores a time without a date.
start_time = models.TimeField()
end_time = models.TimeField()
It can be useful for class timings, office hours, or appointment times.
DurationField stores a duration.
duration = models.DurationField()
It can be useful when an application needs to represent a length of time.
Use auto_now_add=True when a date/time should be automatically set
when the object is first created.
created_at = models.DateTimeField(
auto_now_add=True
)
This is commonly used for record creation timestamps.
Use auto_now=True when a date/time should be automatically updated
whenever the object is saved.
updated_at = models.DateTimeField(
auto_now=True
)
This is useful for tracking the latest update time of a record.
FileField is used for file uploads.
document = models.FileField(
upload_to='documents/'
)
The upload_to option specifies the directory where uploaded files
are stored.
ImageField is used for uploading image files.
photo = models.ImageField(
upload_to='students/'
)
Image uploads also require appropriate media configuration in a Django project.
SlugField is commonly used for URL-friendly text.
slug = models.SlugField(
unique=True
)
Example value:
django-model-fields
Slugs are commonly used in blog and article URLs.
UUIDField stores universally unique identifiers.
import uuid
unique_id = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True
)
UUIDs can be useful when an application needs identifiers other than simple sequential integer IDs.
JSONField can store JSON-compatible data.
details = models.JSONField(
default=dict
)
It can be useful when structured data needs to be stored in JSON format. Database support and behavior depend on the database backend and Django version.
Django model fields support many options that control how data is stored and validated.
Common options include:
nullblankdefaultuniqueeditabledb_indexhelp_textverbose_name
The null and blank options have different meanings.
phone = models.CharField(
max_length=15,
blank=True
)
blank=True affects validation, especially forms. The
null option concerns database storage of NULL.
The unique=True option requires values in that field to be unique
in the database.
email = models.EmailField(
unique=True
)
This can be useful when duplicate values should not be allowed.
The default option provides a value when one is not supplied.
is_active = models.BooleanField(
default=True
)
city = models.CharField(
max_length=50,
default="Aurangabad"
)
The default value should match the purpose and type of the field.
The db_index=True option requests a database index for a field.
Indexes can improve the performance of certain database lookups.
student_id = models.CharField(
max_length=20,
db_index=True
)
Indexes should be used thoughtfully because they also have storage and write costs.
Django also provides fields for connecting models with each other.
ForeignKey – many-to-one relationshipOneToOneField – one-to-one relationshipManyToManyField – many-to-many relationshipclass Student(models.Model):
name = models.CharField(max_length=100)
Relationships will be studied in detail in later lessons.
from django.db import models
class Student(models.Model):
name = models.CharField(
max_length=100
)
email = models.EmailField(
unique=True
)
age = models.PositiveIntegerField()
fee = models.DecimalField(
max_digits=10,
decimal_places=2
)
admission_date = models.DateField()
is_active = models.BooleanField(
default=True
)
description = models.TextField(
blank=True
)
photo = models.ImageField(
upload_to='students/',
blank=True
)
created_at = models.DateTimeField(
auto_now_add=True
)
This example demonstrates several commonly used Django model fields and options.
Django provides many built-in model fields so that developers can represent different types of application data.
CharField – short textTextField – longer textIntegerField – integersDecimalField – precise decimal valuesFloatField – floating-point valuesBooleanField – true or falseEmailField – email addressesURLField – URLsDateField – datesDateTimeField – dates and timesTimeField – timesFileField – file uploadsImageField – image uploadsSlugField – URL-friendly textUUIDField – UUID valuesJSONField – JSON-compatible dataCharField is commonly used for short text.TextField is useful for larger text.IntegerField stores integer values.DecimalField is useful for precise decimal values such as fees.DateField and DateTimeField store date-related data.FileField and ImageField support file uploads.unique=True can prevent duplicate field values.default provides a default value.ForeignKey, OneToOneField, and
ManyToManyField.Question: Which Django model field is commonly used to store short text?