Backend Development 5 min read

Using Django Models to Create Database Tables

This guide explains how to define Django model classes, map them to database tables, and use the makemigrations and migrate commands to generate and apply migrations, illustrated with Users and Files examples and the resulting SQL schema.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Django Models to Create Database Tables

Django models provide a single, definitive source of information about your data, mapping each model to a database table. Each model is a Python class that inherits from django.db.models.Model , and each attribute corresponds to a database column.

Example Users model:

from django.db import models

# Create your models here.
class Users(models.Model):
    # 用户名 - CharField()
    uname = models.CharField(max_length=14)
    # 密码 - CharField()
    upwd = models.CharField(max_length=18)
    # 用户昵称
    nkname = models.CharField(max_length=10)
    # 用户邮箱!
    email = models.EmailField(max_length=50)
    # 启用/禁用 - BooleanField(),默认值为True
    isActive = models.BooleanField(default=True)

The above model generates a table with fields uname, upwd, nkname, email, isActive . The resulting SQL looks like:

create table land_users (
    id int auto_increment primary key,
    upwd varchar(18) not null,
    uname varchar(14) not null,
    nkname varchar(10) not null,
    email varchar(50) not null,
    isActive tinyint(1) not null
);

Similarly, a Files model can be defined:

class Files(models.Model):
    # 文件名
    wenjian = models.CharField(max_length=20)
    # 文件路径
    lujing = models.CharField(max_length=60)
    # 拥有此文件用户
    uname = models.CharField(max_length=14)
    # 用户如何拥有的文件,默认True为上传,False为别人共享
    isActive = models.BooleanField(default=True)
    # 共享给我的用户名,默认为null
    shareduser = models.CharField(max_length=14)

After modifying models, run the following commands to synchronize the database:

python manage.py makemigrations
python manage.py migrate

makemigrations generates migration files (e.g., 0001_initial.py ) that describe the changes, while migrate applies those migrations to the database. It is advisable to review the output of makemigrations before executing migrate , especially after complex changes.

If you change your mind after creating migrations, you can delete the generated migration files before running migrate .

backendpythondatabaseDjangoORMmodels
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.