Django数据库操作

一、初始化框架相关数据库

Django框架默认内置了一些app,这些app是需要数据库支撑的,我们可以先在helloWorld\settings.py中进行数据库配置(这里使用默认配置):

然后再执行下面的命令来生成相关的数据库表

python manage.py migrate

输出内容如下图:

二、初始化app及models.py

2.1、新建一个app(ch3)并做好相关配置,然后我们修改ch3\models.py(这部分的内容可以直接参考Django官网的模型部分)。

ch3\models.py内容如下:

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

2.2、执行下面的指令生成迁移文件:

python manage.py makemigrations ch3

迁移文件在ch3目录下的migrations目录,如图:

文件具体内容请自行查看。

2.3、查看SQL,请执行下面的命令

python manage.py sqlmigrate ch3 0001

命令行显示如下:

BEGIN;

--

-- Create model Question

--

CREATE TABLE "ch3_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

--

-- Create model Choice

--

CREATE TABLE "ch3_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" bigint NOT NULL REFERENCES "ch3_question" ("id") DEFERRABLE INITIALLY DEFERRED);

CREATE INDEX "ch3_choice_question_id_037088df" ON "ch3_choice" ("question_id");

COMMIT;

2.4、生成相应的数据库表

再次执行:

python manage.py migrate

 

三、增删改查

这里我们直接上代码

1、定义路由(ch3\urls.py)

from django.urls import path
from . import views

app_name = "ch3"
urlpatterns = [
    path("", views.index, name="index"),
    path("add_new", views.add_new, name="add_new"),
    path("do_add_new", views.do_add_new, name="do_add_new"),
    path("do_clear", views.do_clear, name="do_clear"),
    path("go_edit", views.go_edit, name="go_edit"),
    path("do_edit", views.do_edit, name="do_edit"),
    path("do_delete", views.do_delete, name="do_delete"),
]

2、路由函数(ch3\views.py)

from django.shortcuts import render, reverse, redirect
from django.http import HttpRequest, HttpResponse, HttpResponseServerError
from django.core.paginator import Paginator
from .models import Question, Choice
from django.utils import timezone


def index(request):
    page_no = request.GET.get('page', default=1)
    page_size = request.GET.get('page_size', default=5)
    questions = Question.objects.all().order_by('-pub_date')
    paginator = Paginator(questions, page_size)
    page_obj = paginator.get_page(page_no)
    return render(request, 'ch3/index.html', {'page_obj': page_obj, 'total': paginator.count})


def add_new(request):
    return render(request, 'ch3/add_new.html')


def do_add_new(request: HttpRequest):
    question_text = request.POST.get('question_text', default='')
    if question_text == '':
        return HttpResponseServerError("问题内容不能为空!")
    q = Question(question_text=question_text, pub_date=timezone.now())
    q.save()
    return redirect(reverse('ch3:index'))


def do_clear(request: HttpRequest):
    Question.objects.all().delete()
    return redirect(reverse('ch3:index'))


def go_edit(request: HttpRequest):
    obj_id = request.GET.get('id', default=0)
    question = Question.objects.get(id=obj_id)
    return render(request, 'ch3/go_edit.html', {"question": question})


def do_edit(request: HttpRequest):
    obj_id = request.POST.get('id')
    pub_date = request.POST.get('pub_date')
    question_text = request.POST.get('question_text', default='')
    if question_text == '':
        return HttpResponseServerError("问题内容不能为空!")
    q = Question(id=obj_id, question_text=question_text, pub_date=pub_date)
    q.save()
    return redirect(reverse('ch3:index'))


def do_delete(request: HttpRequest):
    obj_id = request.GET.get('id', default=0)
    Question.objects.filter(id=obj_id).delete()
    return redirect(reverse('ch3:index'))

3、视图代码

3.1、ch3\index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ch3</title>
    <style>
        #container{
            width: 90%;
            margin: 0 auto;
        }
        table{
            width: 100%;
            border:1px solid blue;
            border-collapse: collapse;
        }
        th,td{
            border:1px solid blue;
            padding: 5px;
        }
        .center{
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        function add_new(){
            window.location.href="{% url 'ch3:add_new' %}"
        }
        function do_clear(){
            window.location.href="{% url 'ch3:do_clear' %}"
        }
        function go_edit(id){
            window.location.href="{% url 'ch3:go_edit' %}?id="+id
        }
        function do_delete(id){
            window.location.href="{% url 'ch3:do_delete' %}?id="+id
        }
    </script>
</head>
<body>
    <div id="container">
        <h1>ch3</h1>
        <a href="{% url 'index' %}">返回主页</a>
        <div style="float: right;margin: 10px;">
            <button onclick="add_new()">新增记录</button>
            <button onclick="do_clear()">清空记录</button>
        </div>
        <table>
            <thead>
            <tr>
                <th style="width: 15%;">ID</th>
                <th style="width: 50%;">问题</th>
                <th style="width: 20%;">发布时间</th>
                <th style="width: 15%;">操作</th>
            </tr>
            </thead>
            <tbody>
            {% if total > 0 %}
                {% for item in page_obj %}
                    <tr>
                        <td>{{ item.id }}</td>
                        <td>{{ item.question_text }}</td>
                        <td>{{ item.pub_date|date:"Y-m-d H:i:s" }}</td>
                        <td class="center">
                            <button onclick="go_edit({{ item.id }})">编辑</button>
                            <button onclick="do_delete({{ item.id }})">删除</button>
                        </td>
                    </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td style="color: red;text-align: center;" colspan="4">没有可以显示的数据!</td>
                </tr>
            {% endif %}
            </tbody>
        </table>
        <div class="pagination">
            <span class="step-links">
                {% if page_obj.has_previous %}
                    <a href="?page=1">&laquo; 首页</a>
                    <a href="?page={{ page_obj.previous_page_number }}">&lsaquo; 上一页</a>
                {% endif %}

                <span class="current">
                    第 {{ page_obj.number }} 页 / 共 {{ page_obj.paginator.num_pages }} 页
                </span>

                {% if page_obj.has_next %}
                    <a href="?page={{ page_obj.next_page_number }}">下一页 &rsaquo;</a>
                    <a href="?page={{ page_obj.paginator.num_pages }}">尾页 &raquo;</a>
                {% endif %}
            </span>
        </div>
    </div>

</body>
</html>

3.2、ch3\add_new.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_new</title>
</head>
<body>
    <h1>add_new</h1>
    <a href="{% url 'ch3:index' %}">返回ch3</a>
    <form method="post" action="/ch3/do_add_new">
        {% csrf_token %}
        <label>问题内容:</label>
        <input type="text" name="question_text" autocomplete="off"/>
        <button type="submit">提交</button>
    </form>
</body>
</html>

3.3、ch3\go_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add_new</title>
</head>
<body>
    <h1>add_new</h1>
    <a href="{% url 'ch3:index' %}">返回ch3</a>
    <form method="post" action="/ch3/do_edit">
        {% csrf_token %}
        <input type="hidden" name="id" value="{{ question.id }}"/>
        <input type="hidden" name="pub_date" value="{{ question.pub_date|date:"Y-m-d H:i:s" }}"/>
        <label>问题内容:</label>
        <input type="text" name="question_text" autocomplete="off" value="{{ question.question_text }}"/>
        <button type="submit">提交</button>
    </form>
</body>
</html>

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django中进行数据库操作需要进行以下几个步骤: 1. 在settings.py文件中配置数据库连接信息。可以使用sqlite3或者MySQL等不同的数据库引擎。例如,如果要连接MySQL数据库,需要将DATABASES中的ENGINE设置为'django.db.backends.mysql',并指定HOST、PORT、NAME、USER和PASSWORD等相关参数。 2. 在views.py文件中编写对数据库操作代码。可以使用Django的ORM(对象关系映射)来进行数据库操作。例如,可以使用models.UserInfo.objects.create()创建一个新的数据库对象,并指定相应的属性值。 3. 在视图函数中处理用户的请求,根据请求的方法(GET或POST)执行相应的数据库操作。例如,可以在POST请求中通过request.POST获取用户提交的表单数据,并使用models.UserInfo.objects.create()将数据写入数据库。 4. 在模板中展示数据库中的数据。可以通过查询数据库获取相应的数据,并将其传递给模板进行展示。例如,可以使用models.UserInfo.objects.all()获取所有的数据库对象,并将其传递给模板进行渲染。 需要注意的是,在进行数据库操作之前,需要确保数据库已经创建并正确配置了相关的权限和表结构。可以在settings.py文件中的DATABASES配置中指定数据库名称、用户名和密码等信息。 总结起来,进行Django数据库操作的主要步骤包括配置数据库连接信息、编写数据库操作代码、处理用户请求以及在模板中展示数据。123 #### 引用[.reference_title] - *1* [Django数据库操作](https://blog.csdn.net/m0_65883616/article/details/125736469)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *2* *3* [django基础之数据库操作](https://blog.csdn.net/inexaustible/article/details/107981925)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值