Defining Models

Loading concept...

Django Models: Your Data’s Blueprint 🏗️

Imagine you’re building a LEGO city. Before placing any brick, you need a plan — where the houses go, how tall the buildings are, what colors to use. Django Models are exactly that: blueprints for your data.


🌟 The Big Picture: Models Overview

Think of a Model like a recipe card in your kitchen.

  • The recipe card tells you: What ingredients you need (fields)
  • It also tells you: How much of each (field options)
  • And sometimes: Pick one from these choices (field choices)
  • Every recipe has a unique number so you never mix them up (primary key)

In Django, a Model is a Python class that describes what data looks like and how it behaves.

# This is like a recipe card!
from django.db import models

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    cook_time = models.IntegerField()

What happens behind the scenes? Django takes your model and creates a database table automatically. Each field becomes a column. Magic! ✨

graph TD A[Python Model] --> B[Django] B --> C[Database Table] C --> D[Rows of Data]

🎨 Defining Models: Building Your Blueprint

Creating a model is like filling out a form for a new student at school.

Step 1: Import the tools

from django.db import models

Step 2: Create your class

class Student(models.Model):
    name = models.CharField(max_length=50)
    age = models.IntegerField()
    email = models.EmailField()

What each part means:

Part What it does
class Student Your blueprint’s name
models.Model Tells Django “this is a Model”
name = ... A text field for names
age = ... A number field for age
email = ... A special field for emails

Real-World Example: A Pet Store App

class Pet(models.Model):
    name = models.CharField(max_length=50)
    species = models.CharField(max_length=30)
    age = models.IntegerField()
    is_adopted = models.BooleanField(default=False)

This creates a table like:

id name species age is_adopted
1 Buddy Dog 3 False
2 Whiskers Cat 5 True

⚙️ Field Options Overview: The Fine Print

Field options are like settings for each ingredient in your recipe.

Common Field Options:

1. null — Can this be empty in the database?

middle_name = models.CharField(
    max_length=50,
    null=True  # Database can store NULL
)

2. blank — Can the user leave it empty?

nickname = models.CharField(
    max_length=30,
    blank=True  # Forms accept empty values
)

💡 Remember: null is for the database. blank is for forms.

3. default — What value if nothing is given?

score = models.IntegerField(default=0)

4. unique — No duplicates allowed!

email = models.EmailField(unique=True)

5. verbose_name — A human-friendly label

dob = models.DateField(
    verbose_name="Date of Birth"
)

Quick Reference Card:

graph TD A[Field Options] --> B[null] A --> C[blank] A --> D[default] A --> E[unique] A --> F[verbose_name] B --> B1[Database NULL ok] C --> C1[Form empty ok] D --> D1[Fallback value] E --> E1[No duplicates] F --> F1[Nice label]

🎯 Field Choices Option: Pick One From the List

Sometimes you want users to pick from specific options only — like a dropdown menu.

How it works:

class Shirt(models.Model):
    SIZE_CHOICES = [
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
        ('XL', 'Extra Large'),
    ]

    size = models.CharField(
        max_length=2,
        choices=SIZE_CHOICES,
        default='M'
    )

What’s in the tuple?

  • First value ('S'): Stored in database
  • Second value ('Small'): Shown to users

Another Example: Order Status

class Order(models.Model):
    STATUS_CHOICES = [
        ('P', 'Pending'),
        ('S', 'Shipped'),
        ('D', 'Delivered'),
        ('C', 'Cancelled'),
    ]

    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='P'
    )

Getting the Display Value:

order = Order.objects.get(id=1)
print(order.status)  # 'P'
print(order.get_status_display())  # 'Pending'

🎁 Bonus: Django gives you get_FIELDNAME_display() automatically!


🔑 Primary Keys: Your Data’s Fingerprint

Every row in your database needs a unique ID — like your fingerprint or student ID number.

The Default: Auto-Generated ID

By default, Django creates this for you:

# Django secretly adds this:
id = models.AutoField(primary_key=True)

Each new record gets the next number: 1, 2, 3, 4…

Custom Primary Key

Want something different? No problem!

class Book(models.Model):
    isbn = models.CharField(
        max_length=13,
        primary_key=True
    )
    title = models.CharField(max_length=200)

Now isbn is the unique identifier instead of id.

UUID Primary Key (Random Unique IDs)

For extra security or distributed systems:

import uuid
from django.db import models

class SecureDocument(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False
    )
    title = models.CharField(max_length=100)

This creates IDs like: 550e8400-e29b-41d4-a716-446655440000

Primary Key Types Comparison:

Type Example Best For
AutoField 1, 2, 3 Simple apps
CharField “ABC123” Existing IDs
UUIDField “550e…” Security, APIs
graph TD A[Primary Key] --> B[AutoField] A --> C[Custom Field] A --> D[UUIDField] B --> B1[1, 2, 3...] C --> C1[ISBN, SKU] D --> D1[Random UUID]

🎉 Putting It All Together

Here’s a complete model using everything we learned:

import uuid
from django.db import models

class Product(models.Model):
    # Primary Key - UUID for uniqueness
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False
    )

    # Basic fields with options
    name = models.CharField(
        max_length=100,
        verbose_name="Product Name"
    )

    description = models.TextField(
        blank=True,
        null=True
    )

    price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0.00
    )

    # Choices field
    CATEGORY_CHOICES = [
        ('E', 'Electronics'),
        ('C', 'Clothing'),
        ('F', 'Food'),
        ('B', 'Books'),
    ]
    category = models.CharField(
        max_length=1,
        choices=CATEGORY_CHOICES
    )

    # Unique constraint
    sku = models.CharField(
        max_length=20,
        unique=True
    )

    is_active = models.BooleanField(default=True)

📝 Key Takeaways

  1. Models are Python classes that define your data structure
  2. Fields are the columns in your database table
  3. Field Options customize how each field behaves
  4. Choices limit a field to specific options
  5. Primary Keys uniquely identify each record

You now have the blueprint skills! Go build amazing data structures with confidence. 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.