Model Fields

Fields declare the type and rules for each column.

Every attribute on a model is a field that maps to a column and controls its type and validation.

FieldStores
CharFieldShort text (needs max_length).
TextFieldLong text.
IntegerFieldWhole numbers.
BooleanFieldTrue / False.
DateTimeFieldDate and time.
EmailFieldValidated email text.
ForeignKeyA link to another model.

Common options include null, blank, default, unique and choices.

Example

Example · python
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)

When to use it

  • A developer uses SlugField to store URL-friendly identifiers for blog posts and adds unique=True to prevent duplicates.
  • A team uses DecimalField for product prices to avoid floating-point rounding errors in financial calculations.
  • A developer uses ImageField with an upload_to path to let users upload profile photos stored on the server.

More examples

Common field types

Demonstrates several common field types used in a typical e-commerce product model.

Example · python
class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    stock = models.PositiveIntegerField(default=0)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

Field options: null, blank, default

Shows when to use null vs blank: null for database NULLs on non-text fields, blank for form validation.

Example · python
class UserProfile(models.Model):
    bio = models.TextField(blank=True, default="")
    birth_date = models.DateField(null=True, blank=True)
    avatar = models.ImageField(
        upload_to="avatars/",
        null=True,
        blank=True,
    )

Choice field with enum

Uses TextChoices to define a set of named constants for a CharField with a fixed set of values.

Example · python
class Order(models.Model):
    class Status(models.TextChoices):
        PENDING = "PE", "Pending"
        PAID = "PA", "Paid"
        SHIPPED = "SH", "Shipped"

    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.PENDING,
    )

Discussion

  • Be the first to comment on this lesson.