Lesson 25 of 60 – Django Model Fields
42%

Django Model Fields

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.

Note: Choosing the correct model field is important because different fields are designed for different types of data such as text, numbers, dates, emails, files, and relationships.

1. What is a Model Field?

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.

2. Importing Django Models

Before defining fields, import Django's models module.

from django.db import models

The models module provides many built-in field types.

3. CharField

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.

4. TextField

TextField is commonly used for larger amounts of text.

description = models.TextField()

It can be used for:

  • Descriptions
  • Comments
  • Articles
  • Long messages
  • Blog content

5. IntegerField

IntegerField is used for integer numbers.

age = models.IntegerField()
marks = models.IntegerField()
quantity = models.IntegerField()

It is useful when decimal values are not required.

6. PositiveIntegerField

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.

7. DecimalField

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.

8. FloatField

FloatField stores floating-point numbers.

rating = models.FloatField()

It can be useful for measurements or values where floating-point representation is appropriate.

9. BooleanField

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)

10. EmailField

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)

11. URLField

URLField is used for storing URLs.

website = models.URLField()

Example:

https://example.com

12. DateField

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.

13. DateTimeField

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
)

14. TimeField

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.

15. DurationField

DurationField stores a duration.

duration = models.DurationField()

It can be useful when an application needs to represent a length of time.

16. Auto Created Date

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.

17. Automatically Updated Date

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.

18. FileField

FileField is used for file uploads.

document = models.FileField(
    upload_to='documents/'
)

The upload_to option specifies the directory where uploaded files are stored.

19. ImageField

ImageField is used for uploading image files.

photo = models.ImageField(
    upload_to='students/'
)

Image uploads also require appropriate media configuration in a Django project.

20. SlugField

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.

21. UUIDField

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.

22. JSONField

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.

23. Field Options

Django model fields support many options that control how data is stored and validated.

Common options include:

  • null
  • blank
  • default
  • unique
  • editable
  • db_index
  • help_text
  • verbose_name

24. null and blank

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.

25. unique Option

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.

26. default Option

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.

27. db_index Option

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.

28. Relationship Fields

Django also provides fields for connecting models with each other.

  • ForeignKey – many-to-one relationship
  • OneToOneField – one-to-one relationship
  • ManyToManyField – many-to-many relationship
class Student(models.Model):
    name = models.CharField(max_length=100)

Relationships will be studied in detail in later lessons.

29. Complete Model Fields Example

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.

30. Summary of Django Model Fields

Django provides many built-in model fields so that developers can represent different types of application data.

  • CharField – short text
  • TextField – longer text
  • IntegerField – integers
  • DecimalField – precise decimal values
  • FloatField – floating-point values
  • BooleanField – true or false
  • EmailField – email addresses
  • URLField – URLs
  • DateField – dates
  • DateTimeField – dates and times
  • TimeField – times
  • FileField – file uploads
  • ImageField – image uploads
  • SlugField – URL-friendly text
  • UUIDField – UUID values
  • JSONField – JSON-compatible data
  • Relationship fields connect different models.

📌 Key Points

  • Model fields represent database columns.
  • Choose a field according to the type of data you need to store.
  • CharField 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.
  • Django also provides relationship fields such as ForeignKey, OneToOneField, and ManyToManyField.

🧠 Quick Quiz

Question: Which Django model field is commonly used to store short text?