In Django, you rarely write SQL to create tables. Instead you describe your data as Python classes called models, and Django turns them into database tables using migrations. Understanding this pair is the first real step from tutorials to building your own app.
A first model
In models.py of your app:
class Course(models.Model):
title = models.CharField(max_length=120)
duration_months = models.PositiveIntegerField()
created_at = models.DateTimeField(auto_now_add=True)
Each attribute becomes a column. The field type decides the column type and also the validation Django applies in forms and the admin.
Making and applying migrations
python manage.py makemigrationscompares your models with the last migration and writes a new migration file describing the change.python manage.py migrateapplies pending migrations to the database.
Think of migration files as version control for your database structure. Commit them to Git with your code, so every teammate and every server ends up with the same tables.
Relationships between models
Use ForeignKey for one-to-many links. An Enrollment model might have course = models.ForeignKey(Course, on_delete=models.CASCADE). The on_delete rule decides what happens to enrollments if a course is deleted; think about it rather than copying CASCADE everywhere.
Common beginner problems
- Adding a required field to a table that already has rows. Django asks for a default value. Give one, or make the field nullable first.
- Editing old migration files. Avoid it once they have been applied elsewhere; create a new migration instead.
- Forgetting to register the model in
admin.py, then wondering why it is missing from the admin.
Next step
Build a small app with two related models, register them in the admin, and add a few records by hand. Then follow your first Django CRUD project and Django vs Flask.
Django is a core part of our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
Want structured practice with a mentor? See our Python Full Stack training in Bangalore.
