Django Model Field Types

Understanding database fields in Django models

🗄️ What are Model Field Types?

Django model fields define the type of data stored in your database. Each field type maps to a specific database column type and provides validation, ensuring your data is stored correctly and efficiently.


# Simple model with different field types
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    in_stock = models.BooleanField(default=True)
                                    

Database Table Created:

Table: product

Columns: id (auto), name (varchar), price (decimal), in_stock (boolean)

Common Field Types

Django provides various field types to handle different kinds of data. Understanding these fields helps you design efficient database schemas and ensures proper data validation for your applications.

📝

Text Fields

Store text and string data

title = models.CharField(max_length=200)
description = models.TextField()
🔢

Numeric Fields

Store numbers and calculations

age = models.IntegerField()
price = models.DecimalField(max_digits=8, decimal_places=2)
📅

Date/Time Fields

Store dates and timestamps

created_at = models.DateTimeField(auto_now_add=True)
birth_date = models.DateField()

Boolean Fields

Store true/false values

is_active = models.BooleanField(default=True)
is_verified = models.BooleanField()

🔹 CharField - Text with Length Limit

CharField stores short text strings with a maximum length. Perfect for names, titles, and short descriptions.

from django.db import models

class Author(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=100, unique=True)
    
    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Usage Example:

# Create an author
author = Author.objects.create(
    first_name="John",
    last_name="Doe",
    email="[email protected]"
)
# Output: John Doe

🔹 TextField - Long Text Content

TextField stores unlimited text content. Ideal for articles, descriptions, and large text blocks.

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()  # No length limit
    summary = models.TextField(blank=True)  # Optional field
    
    def __str__(self):
        return self.title

Usage Example:

# Create a blog post
post = BlogPost.objects.create(
    title="Django Tutorial",
    content="This is a very long article about Django..."
)
# TextField can store thousands of characters

🔹 IntegerField - Whole Numbers

IntegerField stores whole numbers from -2147483648 to 2147483647. Use for counts, ages, and quantities.

class Product(models.Model):
    name = models.CharField(max_length=100)
    quantity = models.IntegerField(default=0)
    views = models.IntegerField(default=0)
    rating = models.IntegerField(choices=[(1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')])
    
    def __str__(self):
        return self.name

Usage Example:

# Create a product
product = Product.objects.create(
    name="Laptop",
    quantity=50,
    views=1250,
    rating=5
)
# Output: quantity=50, views=1250

🔹 DecimalField - Precise Decimal Numbers

DecimalField stores exact decimal numbers. Essential for money, prices, and precise calculations where accuracy matters.

class Order(models.Model):
    product_name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    tax = models.DecimalField(max_digits=5, decimal_places=2)
    discount = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)
    
    def total(self):
        return self.price + self.tax - self.discount

Usage Example:

# Create an order
order = Order.objects.create(
    product_name="Headphones",
    price=99.99,
    tax=8.50,
    discount=10.00
)
# Output: total = 98.49

🔹 BooleanField - True/False Values

BooleanField stores True or False values. Perfect for flags, status indicators, and yes/no questions.

class User(models.Model):
    username = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    email_verified = models.BooleanField(default=False)
    
    def __str__(self):
        return self.username

Usage Example:

# Create a user
user = User.objects.create(
    username="alice",
    is_active=True,
    is_staff=False
)
# Check status
if user.is_active:
    print("User is active")

🔹 DateField & DateTimeField - Dates and Times

DateField stores dates, DateTimeField stores dates with times. Use auto_now_add for creation timestamps and auto_now for updates.

class Event(models.Model):
    name = models.CharField(max_length=100)
    event_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.name

Usage Example:

from datetime import date

# Create an event
event = Event.objects.create(
    name="Django Conference",
    event_date=date(2025, 6, 15)
)
# created_at and updated_at are set automatically
# Output: 2025-06-15

🔹 EmailField - Email Addresses

EmailField stores and validates email addresses automatically. It ensures proper email format before saving to database.

class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    backup_email = models.EmailField(blank=True, null=True)
    
    def __str__(self):
        return f"{self.name} - {self.email}"

Usage Example:

# Create a contact
contact = Contact.objects.create(
    name="Jane Smith",
    email="[email protected]"
)
# Django validates email format automatically
# Invalid emails will raise ValidationError

🔹 URLField - Web Addresses

URLField stores and validates URLs. It checks for proper URL format including protocol (http/https).

class Website(models.Model):
    name = models.CharField(max_length=100)
    url = models.URLField(max_length=200)
    logo_url = models.URLField(blank=True)
    
    def __str__(self):
        return self.name

Usage Example:

# Create a website entry
website = Website.objects.create(
    name="Django Project",
    url="https://www.djangoproject.com"
)
# URLField validates URL format
# Must include http:// or https://

🔹 FileField & ImageField - File Uploads

FileField handles file uploads, ImageField specifically handles images with additional validation. Both store file paths in database.

class Document(models.Model):
    title = models.CharField(max_length=100)
    file = models.FileField(upload_to='documents/')
    thumbnail = models.ImageField(upload_to='thumbnails/', blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.title

Usage Example:

# In views.py
def upload_document(request):
    if request.method == 'POST':
        doc = Document.objects.create(
            title=request.POST['title'],
            file=request.FILES['file']
        )
        # File saved to media/documents/

🔹 ForeignKey - Relationships

ForeignKey creates many-to-one relationships between models. One record can relate to another, like multiple books by one author.

class Author(models.Model):
    name = models.CharField(max_length=100)
    
    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    published_date = models.DateField()
    
    def __str__(self):
        return self.title

Usage Example:

# Create author and books
author = Author.objects.create(name="J.K. Rowling")
book1 = Book.objects.create(
    title="Harry Potter",
    author=author,
    published_date=date(1997, 6, 26)
)
# Access related objects
print(book1.author.name)  # J.K. Rowling
print(author.book_set.all())  # All books by author

🔹 Common Field Options

All field types support common options that control behavior, validation, and database constraints.

class Article(models.Model):
    # null: Allow NULL in database
    subtitle = models.CharField(max_length=200, null=True)
    
    # blank: Allow empty in forms
    description = models.TextField(blank=True)
    
    # default: Set default value
    status = models.CharField(max_length=20, default='draft')
    
    # unique: Ensure unique values
    slug = models.SlugField(unique=True)
    
    # choices: Limit to specific values
    CATEGORY_CHOICES = [
        ('tech', 'Technology'),
        ('news', 'News'),
        ('sports', 'Sports'),
    ]
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES)
    
    # help_text: Add description
    views = models.IntegerField(default=0, help_text="Number of views")

Field Options Explained:

  • null=True: Database allows NULL values
  • blank=True: Forms allow empty submission
  • default: Value used if none provided
  • unique=True: No duplicate values allowed
  • choices: Dropdown with predefined options

🧠 Test Your Knowledge

Which field type should you use for storing prices?