BudiBadu Logo
Samplebadu

Django by Example: Model Field Types

Django 5.0+

Django models are the single, definitive source of information about your data. They contain the essential fields and behaviors of the data you're storing. This code example demonstrates the most common field types used to map Python attributes to database columns.

Code

from django.db import models

class Product(models.Model):
    # String fields
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)

    # Numeric fields
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock_count = models.IntegerField()
    rating = models.FloatField(null=True)

    # Boolean field
    is_active = models.BooleanField(default=True)

    # Date and Time fields
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    release_date = models.DateField()

    # Specialized fields
    sku = models.UUIDField(editable=False)
    metadata = models.JSONField(default=dict)
    website = models.URLField(blank=True)
    contact_email = models.EmailField()

    def __str__(self):
        return self.name

Explanation

A model serves as the single, definitive source of truth for your data, containing the essential fields and behaviors of the data you are storing. Generally, each model maps to a single database table, with fields translating to specific table columns. Choosing the correct field type is a critical architectural decision that impacts not just data storage, but also validation logic, form widget selection, and database performance. For instance, using a DecimalField instead of a FloatField for monetary values is mandatory to avoid floating-point precision errors that can accumulate over time.

Django provides a comprehensive suite of built-in field types that handle the complex mapping between Python objects and underlying database column types.

  • CharField and TextField: Distinguish between limited-length strings (VARCHAR) and unlimited text (TEXT).
  • IntegerField, FloatField, DecimalField: Handle various numeric data with specific precision requirements.
  • DateTimeField: Manages temporal data, often with timezone awareness.
It is vital to distinguish between null=True (which allows NULL values in the database column) and blank=True (which allows empty values in Django forms). For string-based fields, avoiding null=True is a best practice to prevent ambiguity between an empty string and a NULL value.

Performance optimization often starts at the field definition level. The db_index=True argument can be added to any field to create a database index, which significantly speeds up FILTER, EXCLUDE, and ORDER BY operations involving that column. However, indexes come with a trade-off: they consume additional disk space and slow down INSERT and UPDATE operations because the index must be updated alongside the data. Therefore, indexes should be applied judiciously to fields that are frequently queried but less frequently modified.

Field Breakdown

5-7
CharField is for short strings and requires max_length. TextField is for large text blocks. SlugField is specialized for URLs and often implies uniqueness.
10-12
DecimalField is essential for monetary values to avoid floating-point errors, requiring max_digits and decimal_places. IntegerField and FloatField handle standard numbers.
18-19
auto_now_add=True sets the field to now when the object is first created. auto_now=True updates the field to now every time the object is saved.
23-24
JSONField allows storing arbitrary JSON data (PostgreSQL, MySQL, SQLite). UUIDField is useful for unique identifiers that aren't sequential integers.