Django对数据库表的操作

一、单表操作

M  model.py 

import pymysql

config = {
    'host': '127.0.0.1',
    'user': 'fred_li',
    'password': '835y1354',
    'db': 'assent'
}

class MyModel(object):
    def __init__(self):
        # 连接数据库
        try:
            self.conn = pymysql.connect(**config)
            self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)  # 结果以列表字典形式返回
        except Exception as e:
            print('connect db error', e)

    def get_list(self, sql):
        try:
            self.cur.execute(sql)
            res = self.cur.fetchall()
            return res
        except Exception as e:
            print(e)

    def getone_list(self, sql, args):
        # 查询部分数据
        try:
            self.cur.execute(sql, args)
            res = self.cur.fetchone()
            return res
        except Exception as e:
            print(e)

    def add(self, sql, args):
        try:
            self.cur.execute(sql, args)
            self.conn.commit()
        except Exception as e:
            print('insert to db error', e)

    def modify(self, sql, args):
        try:
            self.cur.execute(sql, args)
            self.conn.commit()
        except Exception as e:
            print('update to db error', e)

    def close_conn(self):
        self.cur.close()
        self.conn.close()
mysql相关操作

V views.py

from django.shortcuts import render, redirect

from app01 import models

def accountinfo(request):
    model = models.MyModel()
    res = model.get_list('select * from accountinfo where state=0')
    model.close_conn()
    return render(request, 'accounts.html', {'accountinfo': res})


def add_account(request):
    '''
    此功能承担两个职责:
        1、在账号列表页面,当点击添加账号时,属于GET操作
        2、跳转到添加账号页面,提交数据则属于POST操作
    :param request:
    :return:
    '''
    model = models.MyModel()
    if request.method == "GET":
        res = model.get_list('select * from accountinfo where state=0')
        model.close_conn()
        return render(request, 'add_account.html', {'accountinfo': res})
    else:
        name = request.POST.get('accountname')
        print(name)
        res = model.add('insert into accountinfo(name) VALUES(%s)', (name))
        model.close_conn()
        return redirect('/accountinfo/')


def modify_account(request):
    model = models.MyModel()
    if request.method == "GET":
        accountid = request.GET.get('accountid')
        res = model.getone_list('select * from accountinfo where state=0 and id=%s', (accountid))
        model.close_conn()
        return render(request, 'modify_account.html', {'accountinfo': res})
    else:
        accountname = request.POST.get('accountname')
        accountid = request.POST.get('accountid')
        model.modify('update accountinfo set name=%s where id=%s', (accountname, accountid))
        model.close_conn()
        return redirect('/accountinfo/')


def del_account(request):
    '''
    此处不是物理删除,只是把账号的state的值由0(正常),改为1(已删除) 
    :param request: 
    :return: 
    '''
    model=models.MyModel()
    accountid=request.GET.get('accountid')
    print(accountid)
    model.modify('update accountinfo set state=1 where id=%s',(accountid))
    model.close_conn()
    return redirect('/accountinfo/')
增删改查

T 静态模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>账号查询</title>
    <link rel="shortcut icon" href="/static/images/icon.jpg">
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <h2>账号列表</h2>
    <a href="/add_account/">添加账号</a>
    <table border="1px">
        <tr>
            <th>账号id</th>
            <th>账号名称</th>
            <th>操作</th>
        </tr>
        {% for item in accountinfo %}
            <tr>
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>
                    <a href="/del_account/?accountid={{ item.id }}" onclick="return doConfirm()">删除</a>
                    <a href="/modify_account/?accountid={{ item.id }}">更新</a>
                </td>
            </tr>
        {% endfor %}
    </table>
</body>
<script>
    function doConfirm() {
        res=window.confirm('是否要删除此账号??')

        if(res){
            return true
        }else {
            return false
        }
    }
</script>
</html>
查询页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加账号</title>
    <link rel="shortcut icon" href="/static/images/icon.jpg">
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <h2>添加账号</h2>
    <!-- action 指定表单向指定url发送数据-->
    <form action="/add_account/" method="post">
        <input type="text" name="accountname" placeholder="请输入账号名称">
        <input type="submit" value="提交">
    </form>
</body>
</html>
新增页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改服务器信息</title>
    <link rel="shortcut icon" href="/static/images/icon.jpg">
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <h2>修改服务器信息</h2>
    <form action="/modify_server/" method="post">
        <input type="hidden" name="serverid" value="{{ serverinfo.id }}">
        <input type="text" name="hostname" value="{{ serverinfo.hostname }}">
        <input type="submit" value="提交">
    </form>

</body>
</html>
修改页面

路由层 urls.py

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


urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^accountinfo/', views.accountinfo),
    url(r'^add_account/', views.add_account),
    url(r'^modify_account/', views.modify_account),
    url(r'^del_account/', views.del_account),
]
# 此处Django版本是1.11.9 url...格式 2.x path....格式

 

原文地址:https://www.cnblogs.com/lichunke/p/10001959.html