Creating and Migrating Database Tables in Django


Introduction

In Django, creating and migrating database tables is a fundamental step when developing web applications. Django's migration system makes it easy to define your data models and keep your database schema up to date as your project evolves. In this guide, we'll explore how to create and migrate database tables in Django.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Django: You should have Django installed. If not, use
    pip install django
    to install it.
  • Django Project: You should have a Django project set up. If not, refer to the guide on creating your first Django project.
  • Models: Ensure you have defined data models in your Django app. If not, refer to the guide on Django models.

Defining Data Models

In Django, data models define the structure of your database tables. Each model class represents a table, and class attributes define fields in the table.


Sample Code

Create a Django model in your app's

models.py
file. For example:

from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=2)

Creating Migrations

Migrations are Django's way of propagating changes you make to your models (such as adding or modifying fields) into your database schema.


Sample Code

Create migrations for your app using the following command:

python manage.py makemigrations yourapp

Applying Migrations

After creating migrations, you need to apply them to your database to create or update the corresponding tables.


Sample Code

Apply migrations using the following command:

python manage.py migrate

Conclusion

Creating and migrating database tables in Django is a crucial part of web application development. By defining data models, creating migrations, and applying them, you can maintain a structured and evolving database schema to support your application's data needs.