Django ORM 基础:模型定义、数据库迁移与增查实现

闻溪
闻溪
发布时间:2026-10-13| 5人浏览过
原创

本文详解 Django ORM 核心概念,通过类映射数据库表、对象代表记录的方式,实现无需编写 SQL 的数据操作。内容涵盖 models.py 模型定义、makemigrations 与 migrate 命令执行数据库迁移,以及利用 views 处理 POST 请求、Book.objects.create() 保存数据和 render 渲染页面,完整演示书籍信息的添加与列表展示流程。

Django ORM 核心概念

ORM(对象关系映射)是 Django 框架的核心特性之一。

传统数据库操作中,数据的增删改查依赖于 SQL 语句。

在 Django 中,开发者可以直接使用 Python 代码对数据库进行增删改查,这一机制即为 ORM。

在 Python 代码中,定义的类名对应 Django 数据库中的表名。

类的实例化对象则代表数据库中的一条具体记录。

ORM 封装了底层的 SQL 语句,允许开发者通过操作对象来完成数据库的增删改查,从而简化数据库交互。

数据库配置与迁移

Django 的 settings 文件中默认配置了 SQLite 数据库,用户可根据需求修改此配置。


DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  }
}<br data-filtered="filtered"><br data-filtered="filtered">BASE_DIR 是代表当前的文件夹 settings,

Django 对数据库结构的变更只需修改相关配置及模型定义即可处理。

===

模型定义与表生成

在 models.py 文件中,需要设计具体的数据表结构。


from django.db import models

# Create your models here.

#继承来自models ,
class Book(models.Model):
  name = models.CharField(max_length=32)
  price = models.IntegerField()
  Date = models.DateField()
  auth = models.CharField(max_length=32)
  publish = models.CharField(max_length=32)

随后在命令行终端中执行相应的迁移命令。


python manage.py makemigrations 
python manage.oy migrate 

这些命令用于生成实际的数据库表结构。

视图逻辑与页面实现

在 templates 目录下创建主页 index.html 文件,用于展示添加书籍后的列表信息。


{% load staticfiles %} #  ------引用静态文件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="{% static '/bootstrap-3.3.7/dist/css/bootstrap.css/' %}" rel="external nofollow" >  # ---导入bootstrap 文件

  <style>

    .container{
      margin-top: 50px;
    }

  </style>

</head>
<body>


<div class="container">
  <div class="row">


    <div class="col-md-6 col-md-offset-2">
    <a href="/addbook/" rel="external nofollow" ><button class="btn btn-primary">添加书籍</button></a>
    <table class="table table-striped">
      <tr>
        <th>ID</th>
        <th>书名</th>
        <th>价格</th>
        <th>出版日期</th>
        <th>作者</th>
        <th>出版社</th>
      </tr>
{#      <tr>#}
{#        <td>1</td>#}
{#        <td>水浒城</td>#}
{#        <td>110</td>#}
{#        <td>2011.1.1</td>#}
{##}
{#        <td>egon</td>#}
{#        <td>人民出版社</td>#}
{#      </tr>#}
{#       <tr>#}
{#        <td>2</td>#}
{#        <td>水浒城</td>#}
{#        <td>110</td>#}
{#        <td>2011.1.1</td>#}
{##}
{#        <td>egon</td>#}
{#        <td>人民出版社</td>#}
{#      </tr>#}
       {% for book in book_list %}  #--从数据库取到的数据是一个QuerySet集合,进行for循环,遍历出每个对象,
      <tr>

          <td>{{ book.id }}</td> #---把每个对象的属性的值渲染出来,
          <td>{{ book.name }}</td>
          <td>{{ book.price }}</td>
          <td>{{ book.Date }}</td>
          <td>{{ book.auth }}</td>
          <td>{{ book.publish }}</td>

      </tr>
      {% endfor %}
    </table>

  </div>
  </div>

</div>
</body>

<script>


</script>

</html>

编写 addbook.html 文件,提供书籍添加表单,提交后跳转至 index 页面。


{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="{% static '/bootstrap-3.3.7/dist/css/bootstrap.css/' %} " rel="external nofollow" >

  <style>
    .container{
      margin-top: 50px;
    }
  </style>

</head>
<body>


<div class="container">

  <div class="row">

    <div class="col-md-6 col-md-offset-2">
{#      {{ csrf-token }}#}
      <form class=addbook" action="/addbook/" method="post">

{#      当点击添加按钮时,是执行视图函数,在数据库中添加一条记录,然后再把这个记录添加到index页面#}

      <div class="form-group">
        <label for="bookname">书名:</label>
        <input type="text" class="form-control" id="bookname" name="bookname">  #---input 中的name属性,用于获取输入的值,
      </div>
      <div class="form-group">
        <label for="price">价格:</label>
        <input type="text" class="form-control" id="price" name="price"> #---input 中的name属性,用于获取输入的值,
      </div>
      <div class="form-group">
        <label for="Date">日期:</label>
        <input type="text" class="form-control" id="Date" name="Date">  #---input 中的name属性,用于获取输入的值,
      </div>
      <div class="form-group">
        <label for="auth">作者:</label>
        <input type="text" class="form-control" id="auth" name="auth">  #---input 中的name属性,用于获取输入的值,
      </div>

      <div class="form-group">
        <label for="publish">出版社:</label>
        <input type="text" class="form-control" id="publish" name="publish">  #---input 中的name属性,用于获取输入的值,
      </div>

      <input class="btn btn-info" type="submit" value='添加'>

      </form>



    </div>
  </div>

</div>


</body>

</html>

在 urls.py 文件中,配置 index 页面和 addbook 页面所对应的视图函数路由。


from django.conf.urls import url
from django.contrib import admin

from app01 import views

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^index/$',views.index),
  url(r'^addbook/$',views.addbook),
]

在 views.py 文件中编写业务逻辑:用户访问 index 页面,点击添加按钮跳转至 addbook 页面录入数据,提交后数据存入数据库,随后从数据库读取数据显示在 index 页面。

步骤1:要在 index 页面显示数据库信息,需导入 Book 模型,获取所有数据,并通过 render 函数渲染到页面进行展示。

步骤2:在 addbook 视图函数中,从 form 表单中获取添加的数据,通过 request 对象以 POST 方法接收。

将数据存入数据库时,使用 create 方法,语法为:表名.objects.create(数据库字段名=表单中对应的属性值)。

具体代码示例为:Book.objects.create(name=bookname, price=price, Date=Date, auth=auth, publish=publish)。

上述代码中,等号左侧的 name 是 models.py 中定义的字段名,右侧的值对应从 form 表单中获取的数据。


from django.shortcuts import render,redirect

# Create your views here.
from app01.models import Book

def index(request):

  #把数据库的数据嵌入到页面进行显示
  #查询api,所有书籍
  book_list = Book.objects.all() #数据类型是QuerySet:[book1,book2...]

  return render(request,'index.html',locals())


def addbook(request):

  #是form提交post的方法,
  if request.method == 'POST':
    #从form表单取数据
    bookname = request.POST.get('bookname')
    price = request.POST.get('price')
    Date = request.POST.get('Date')
    auth = request.POST.get('auth')
    publish = request.POST.get('publish')

  #把数据存到数据库,先把models 中的表引导到views文件

  #方法1,左边的name 是models里的字段名,对应到form里取到的值,


    Book.objects.create(name = bookname,price = price, Date = Date, auth = auth , publish = publish)


  #存到数据库后要放到index页面,但现在是addbook页面,所以要跳转

    return redirect('/index/')

  return render(request,'addbook.html')

以上即为 Django ORM 实现数据增加与查询的完整流程,希望有助于理解相关技术。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。