What This Article Will Cover
➡️ How to configure your Django project’s database
➡️ Creating and activating Django models
➡️ Generating and applying migrations
➡️ Using Django’s ORM for database interaction
➡️ Connecting your app to Django admin
➡️ Running queries in the interactive shell
➡️ Best practices for model and migration management
➡️ Using Django’s ORM for database interaction
➡️ Running queries in the interactive shell
➡️ Creating and activating Django models
➡️ Update TIME_ZONE to your region
➡️ Ensure INSTALLED_APPS
Step-by-Step Guide to Django App Part 2
1. Set Up Your Database
- Open polls_project/settings.py
- Default database: SQLite (easy and built-in)
- Optional: Switch to PostgreSQL or MySQL if needed
- Update TIME_ZONE to your region
- Ensure INSTALLED_APPS includes essential Django apps like:
- django.contrib.admin
- django.contrib.auth
- django.contrib.sessions, etc.
- django.contrib.admin
💡 Tip: SQLite is perfect for development. Switch to a robust DB like PostgreSQL in production.
2. Create Your First Models
- Go to polls/models.py
- Define two models:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
# explainations
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" bigint NOT NULL PRIMARY KEY GENERAT
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
# explainations
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
"id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL,
"question_id" bigint NOT NULL
);
ALTER TABLE "polls_choice"
ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
🧠 A Django model defines the structure of your data using Python classes.
3. Register Your App
- Add your app to INSTALLED_APPS:
"polls.apps.PollsConfig",
OR
- "polls",
4. Create and Apply Migrations
- Run:
python manage.py makemigrations polls
python manage.py migrate
🔄 This generates and applies SQL code to build database tables for your models.
5. Explore the Django Shell
- Start shell:
python manage.py shell
- Example usage:
from polls.models import Question
from django.utils import timezone
q = Question(question_text="What's new?",
pub_date=timezone.now())
q.save()
🔍 Use .objects.all(), .get(), .filter() to query your database.
6. Add __str__() and Custom Methods
- Make model output readable in shell/admin:
def __str__(self): return self.question_text - Add useful methods like:
def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
7. Work with Related Models
- Add choices to a question:
q.choice_set.create(choice_text="Not much", votes=0) - Query related objects:
q.choice_set.all()
🔁 Django’s ORM handles relationships like ForeignKey seamlessly.
8. Enable Django Admin for Your App
- Open polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
- Access admin at /admin/ after creating a superuser:
python manage.py createsuperuser
Best Practices & Smart Approach
- ✅ Always commit your migrations to version control.
- ✅ Use makemigrations and migrate as a routine after model changes.
- ✅ Keep your models lean and meaningful — each method should serve a real need.
- ✅ Add readable __str__() methods for clarity in admin and debug output.
- ✅ Use Django shell for quick data testing before writing views.
Conclusion & What to Do Next
You’ve now learned how to define and register Django models, run migrations, work with the Django ORM, and access your app through the admin interface. These are essential building blocks for every Django project, and you’ve mastered them in just a few steps.