Learning Django: A Step-by-Step Guide to Models and Databases
Learning Django: A Step-by-Step Guide to Models and Databases
Introduction
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. One of its core features is the Object-Relational Mapping (ORM) system, which allows developers to interact with databases using Python code. In this guide, we will explore Django models, migrations, and databases from basic to advanced.
1. Setting Up Your Django Project
- Install Django
pip install django
- Create a Django Project
django-admin startproject myproject
cd myproject
- Start the Development Server
python manage.py runserver
- Open
http://127.0.0.1:8000/in your browser to see the Django welcome page.
2. Creating a Simple Django App
- Create an App
python manage.py startapp myapp
- Register the App in
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # Add your app here
]
3. Creating Your First Model
- Define a Model (
models.py)
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100) # Text field with max length 100
lastname = models.CharField(max_length=100) # Text field with max length 100
age = models.IntegerField() # Integer field
address = models.CharField(max_length=255) # Text field for address
email = models.EmailField(unique=True) # Unique email field
enrollment_date = models.DateField(auto_now_add=True) # Auto-filled date field
is_active = models.BooleanField(default=True) # Boolean field to check if the person is active
def __str__(self):
return f"{self.name} {self.lastname}"
4. Working with Migrations in Django
What are Migrations?
Migrations are Django's way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
1. Creating Migrations (makemigrations)
python manage.py makemigrations
- Analyzes your models and creates migration files.
- Example output:
Migrations for 'myapp':
myapp/migrations/0001_initial.py
- Create model Person
2. Applying Migrations (migrate)
python manage.py migrate
- Applies the changes described in migration files to the actual database.
- Example output:
Applying myapp.0001_initial... OK
3. Checking Migration Status
python manage.py showmigrations
- Shows which migrations are applied and which are pending.
4. Rolling Back Migrations
python manage.py migrate myapp 0001
- Rolls back to a specific migration.
Best Practices
- Always run
makemigrationsandmigrateafter model changes. - Check migration status with
showmigrations.
5. Adding Data Using Django Shell
- Open the Django Shell
python manage.py shell
- Add Data to the Model
from myapp.models import Person
# Create a new person
person = Person(name="John", lastname="Doe", age=25, address="New York", email="john@example.com", is_active=True)
person.save()
# Verify the data
Person.objects.all()
- This will output the saved data, showing the person in the database.
6. Using Django Admin Panel
- Create a Superuser
python manage.py createsuperuser
- Register the Model in Admin (
admin.py)
from django.contrib import admin
from .models import Person
admin.site.register(Person)
- Access the Admin Panel
- Visit
http://127.0.0.1:8000/admin/and log in with your superuser credentials.
7. Displaying Data on a Webpage
- Create a View (
views.py)
from django.http import HttpResponse
from .models import Person
def person_list(request):
persons = Person.objects.all()
output = ''
for p in persons:
output += f"Name: {p.name} {p.lastname} (Age: {p.age}), Address: {p.address}, Email: {p.email}, Enrolled on: {p.enrollment_date}, Active: {p.is_active}<br>"
return HttpResponse(output)
- Set Up a URL (
urls.py)
from django.urls import path
from .views import person_list
urlpatterns = [
path('persons/', person_list, name='person_list'),
]
- Connect App URLs in Project (
myproject/urls.py)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
- Test in Browser
- Visit
http://127.0.0.1:8000/persons/to see the list of persons.
8. Next Steps
- Learn Django Templates
- Django Forms and Validation
- CRUD Operations (Create, Read, Update, Delete)
- Model Relationships
- Advanced Querying and Model Methods
Conclusion
This guide covers the basics of creating models, working with migrations, and displaying data in Django. As you become more comfortable with the basics, you can explore more advanced features of Django models and the ORM to build robust and dynamic web applications.
Comments
Post a Comment