Models in Django - potatoscript/django GitHub Wiki

๐Ÿง’ What is a Django Model?

A model in Django is a blueprint for your data.
It tells Django:

  • โœ… What kind of data you want to save (like name, age, photoโ€ฆ)
  • โœ… What type each piece of data is (text, number, imageโ€ฆ)
  • โœ… How to store and retrieve that data from the database

You donโ€™t need to touch SQL directly โ€” Django takes care of that for you! ๐Ÿ™Œ


๐Ÿงฑ Step-by-Step: Creating and Using Models

Letโ€™s build a model step by step. Think of it like creating your own collectible card system! ๐Ÿƒ


๐Ÿ› ๏ธ 1. Define Your Model in models.py

๐Ÿ“„ Inside your app (like myapp/models.py):

from django.db import models

class Toy(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=50)
    age_limit = models.IntegerField()
    is_available = models.BooleanField(default=True)
    added_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} ({self.category})"

๐Ÿง  Whatโ€™s happening?

  • CharField = text
  • IntegerField = number
  • BooleanField = true/false
  • DateTimeField = time added
  • __str__ = what shows in admin panel

๐Ÿงน 2. Register the Model in admin.py

So Django knows we want to manage this model in the admin panel:

๐Ÿ“„ myapp/admin.py

from django.contrib import admin
from .models import Toy

admin.site.register(Toy)

๐Ÿ“‹ 3. Make Migrations (Tell Django About Changes)

In the terminal:

python manage.py makemigrations

๐Ÿ“ฆ This prepares the blueprint.

Then run:

python manage.py migrate

๐Ÿงฑ This builds the actual table in your database!


๐Ÿ”‘ 4. Create a Superuser (If Not Already Done)

python manage.py createsuperuser

๐Ÿšช 5. Log in to Django Admin

Run your server:

python manage.py runserver

Go to:
http://127.0.0.1:8000/admin/

Login with your superuser, and voilร !
Youโ€™ll see the โ€œToyโ€ model you created โ€” ready to add, edit, and delete toy entries! ๐ŸŽ‰


๐Ÿงช 6. Play with the Data from Python (Shell Time!)

Run:

python manage.py shell

Then:

from myapp.models import Toy

# Create a new toy
t1 = Toy(name="Rubik's Cube", category="Puzzle", age_limit=8)
t1.save()

# See all toys
Toy.objects.all()

# Find specific toys
Toy.objects.filter(category="Puzzle")

๐Ÿ” Full Example

Hereโ€™s a full Django app model setup:

๐Ÿ“‚ mytoys/

models.py
admin.py
views.py

๐Ÿ“„ models.py

from django.db import models

class Toy(models.Model):
    name = models.CharField(max_length=100)
    color = models.CharField(max_length=30)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    added = models.DateField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} - ${self.price}"

๐Ÿ“„ admin.py

from django.contrib import admin
from .models import Toy

@admin.register(Toy)
class ToyAdmin(admin.ModelAdmin):
    list_display = ('name', 'price', 'color', 'in_stock', 'added')
    list_filter = ('in_stock', 'color')
    search_fields = ('name',)

๐Ÿ“Œ Model Field Types (Like LEGO Blocks ๐Ÿงฑ)

Field Type What It Does Example
CharField Small text Name, Category
TextField Long text Description, Bio
IntegerField Whole number Age, Quantity
BooleanField True/False Available, Published
DateTimeField Date and time Created on, Updated at
DecimalField Decimal numbers Price, Ratings
ImageField Upload image Profile pic, Product image
ForeignKey Connect to another model Author of Post, Owner of Toy

๐ŸŽฏ What Can You Do with Models?

  • Create forms from models automatically ๐Ÿ“
  • Query data easily (.filter(), .exclude(), .get())
  • Use model data in your views and templates
  • Save and update data from user input