Django Models - Creating Database Tables


Introduction

Django models play a central role in building database-driven web applications. They define the structure of your database tables, allowing you to work with data in a Pythonic way. In this guide, we'll explore how to create database tables using Django models.


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 already set up. If not, refer to the guide on creating your first Django project.

Creating a Django Model

To create a database table in Django, you need to define a model. Models are Python classes that represent database tables. You define the fields of the table as class attributes in your model.


Sample Code

Let's create a simple example of a Django model. In this case, we'll define a model for a "Product" table.


models.py

In your Django app, create a models.py file and define the model as follows:

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

Creating Database Tables

Once you've defined your model, you need to create the corresponding database table. To do this, you'll use Django's migration system. Migrations are like version control for your database schema.


Sample Code

Run the following commands in your command prompt or terminal to create and apply migrations:

python manage.py makemigrations
python manage.py migrate

Conclusion

You've learned how to create database tables using Django models. Models provide a powerful way to define your database schema, and migrations help you keep your database structure in sync with your code.