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! ๐
models.py
๐ ๏ธ 1. Define Your Model in ๐ 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
= textIntegerField
= numberBooleanField
= true/falseDateTimeField
= time added__str__
= what shows in admin panel
admin.py
๐งน 2. Register the Model in 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
- Username:
admin
- Email:
[email protected]
- Password:
********
๐ช 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