Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

django
python
communitycreator

How to create a data model in Django

Shubham Singh Kshatriya

In Django, models is a built-in Python class that is used to create tables, their fields, and various constraints. Each model is a subclass of the django.db.models.Model class and maps to a single table in a database. Each attribute of the model represents a database field.

How to create a model

Every Django app has a models.py file where the models are created. The code snippet below creates a simple model named Product that has two fields, name and price:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField()

Explanation

  • The models class is imported from django.db and creates a class Product that accepts models.Model as an argument.

  • CharField stores values that are of string type and accepts a required parameter max_length that specifies the maximum allowed length of the input.

  • IntegerField stores values that are of the integer type.

How to map a model to a table

Django maps the fields defined in Django models into table fields of the database. While mapping, Django will create an ID field by itself.

Below is an illustration of how mapping works:

Whenever you create, update, or delete a model, you need to run two commands in any of the models.py files of the project:

  1. make migrations: This command generates a SQLStructured Query Language query to create the model as a table in our database.

Make sure to add the project in preinstalled apps in settings.py.

python manage.py makemigrations
  1. migrate: This command creates the table in our database.
python manage.py migrate

The commands above create a model and map it onto a table. With this, you are all set to add, delete, update, or read data from your database.

RELATED TAGS

django
python
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring