python-backend
/

Django Models – Designing Your Database

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Django Models – Designing Your Database

What is a Django Model?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. In Django, models are Python classes that subclass django.db.models.Model. Django uses these classes to automatically create the database tables for you via the ORM (Object-Relational Mapper).

  1. Defining Fields

Each attribute of the model represents a database field. Django provides a wide variety of field types that handle validation and SQL mapping automatically.

PythonRead-only
1
from django.db import models

class Project(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    stars = models.IntegerField(default=0)

    def __str__(self):
        return self.title

  1. Database Relationships

Django handles the three most common types of database relationships with ease: One-to-Many, Many-to-Many, and One-to-One.

  • ForeignKey: Defines a many-to-one relationship (e.g., many Tasks belong to one Project).
  • ManyToManyField: Defines a many-to-many relationship (e.g., a Project can have many Tags, and a Tag can be on many Projects).
  • OneToOneField: Defines a one-to-one relationship (e.g., a User has exactly one Profile).

  1. Migrations: Evolving Your Schema

Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. It’s a two-step process:

BASHRead-only
1
# 1. Scan models and create a set of instructions
python manage.py makemigrations

# 2. Execute the instructions on the database
python manage.py migrate

Common Model Fields

Field TypeUsageSQL Equivalent
CharFieldShort to medium stringsVARCHAR
TextFieldLarge amounts of textTEXT / LONGTEXT
EmailFieldStrings with email validationVARCHAR
DateTimeFieldDate and time objectsDATETIME
DecimalFieldFixed-precision decimals (Money)DECIMAL
SlugFieldURL-friendly strings (hyphenated)VARCHAR

Test Your Knowledge

Q1
of 3

Which command is used to sync your database with your model changes?

A
python manage.py runserver
B
python manage.py sync
C
python manage.py migrate
D
python manage.py update
Q2
of 3

Which field type would you use for a blog post content?

A
CharField
B
TextField
C
StringField
D
ContentField
Q3
of 3

What is the purpose of the __str__ method in a Model?

A
To convert the model to JSON
B
To provide a human-readable name for the object in the Admin panel
C
To save the object to the database
D
To encrypt sensitive strings

Frequently Asked Questions

What is the ORM?

The ORM (Object-Relational Mapper) allows you to interact with your database using Python code instead of writing raw SQL. For example, 'Project.objects.all()' replaces 'SELECT * FROM project;'.

What does 'on_delete=models.CASCADE' do?

It defines the behavior when a referenced object is deleted. CASCADE means if the 'Parent' is deleted, all 'Child' records referencing it will also be deleted.

Can I use an existing database with Django?

Yes. Django has an 'inspectdb' utility that can scan an existing database and automatically generate the Model classes for you.

Previous

django mvc mvt

Next

django views

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.