This section covers the basics of models and migrations in Django, which are essential components for building and maintaining a database-driven web application.
Models
Django models are Python classes that define the structure of your database tables. They are used to create objects that correspond to rows in the database tables.
- Fields: Each model has fields that represent the columns in the database table. Common fields include
CharField
,IntegerField
,DateTimeField
, and many more. - Relationships: Models can be related to each other using foreign keys, one-to-one, many-to-one, and many-to-many relationships.
- Managers: Each model has a manager that provides methods for querying and manipulating the database records.
For more information on Django models, you can read the official Django documentation.
Migrations
Django migrations are the way you change your database schema over time. They are used to track changes to your models and apply those changes to your database.
- Creating Migrations: When you add a new field to a model, delete a model, or change a field type, Django will automatically generate a migration for you.
- Applying Migrations: You can apply migrations to update your database schema. This can be done using the
migrate
command. - Unapplying Migrations: If you need to revert a migration, you can use the
unmigrate
command.
For more information on Django migrations, you can read the official Django documentation.