溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

三、2:使用orm制作表圖的增、刪、改、查

發(fā)布時間:2020-07-30 18:03:20 來源:網(wǎng)絡 閱讀:254 作者:a120518129 欄目:編程語言

一、首先配置orm

1、首先在settings.py中配置(數(shù)據(jù)庫需要手動提前先建好)

注釋以下內(nèi)容(47行)

# 'django.middleware.csrf.CsrfViewMiddleware',
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'orm_db1',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'USER':'root',
        'PASSWORD':'mariadb.123',
    }
}

2、在__init__.py中添加以下內(nèi)容:

import pymysql
pymysql.install_as_MySQLdb()

二、在項目中配置

1、在models.py中創(chuàng)建用戶表與字段填寫

from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    address = models.CharField(max_length=32)
    phone=models.CharField(max_length=64,default='120')
#______________ 分割線,另做其他使用___________________________
class Publish(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    email = models.EmailField()
    addr = models.CharField(max_length=64)

class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    address = models.CharField(max_length=32)

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    # 21.38
    price = models.DecimalField(max_digits=5, decimal_places=2)
    # 一對多的關(guān)系確立,關(guān)聯(lián)字段寫在多的一方,orm自動在publish后面加id,publish_id
    publish = models.ForeignKey(to='Publish', to_field='id')
    # 多對多關(guān)系,orm會自動創(chuàng)建第三張表
    authors = models.ManyToManyField(to='Author')

1 python3 manage.py makemigrations   ----記錄一下數(shù)據(jù)庫的變化

2 python3 manage.py migrate          ----將變化同步到數(shù)據(jù)庫中

2、在總路由添加以后可能要添加的功能路由地址與對應的視圖

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^user_list/',views.user_list),
    url(r'^delete/',views.delete),
    url(r'^add/',views.add),
    url(r'^edit/',views.edit),
]

3、在視圖功能文件中填寫:views.py

from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here.
def user_list(request):
    if request.method=='GET':
        # 查詢user表中所有數(shù)據(jù).--相當于sql select * from app01_user;
        # 返回結(jié)果是QuerySet對象(先當成列表)
        # [user1,user2]
        # 單表查詢所有用戶
        ret=models.User.objects.all()
        # print(type(ret))
        # for i in ret:
        #     print(type(i))
        #     print(i.name)
        return render(request,'user_list.html',{'user_list':ret})
def delete(request):
# get請求攜帶參數(shù):http://127.0.0.1:8000/deleteuser/?id=1
    if request.method=='GET':
       # 后臺取值:request.GET.get('id')
        id=request.GET.get('id')
        # orm刪除記錄
        models.User.objects.filter(id=id).delete()
        return redirect('/user_list/')
def add(request):
    if request.method=='GET':
        return render(request, 'add.html')
    elif request.method=="POST":
            # 前臺post提交的數(shù)據(jù)取值:
        name=request.POST.get('name')
        pwd=request.POST.get('password')
        addr=request.POST.get('addr')
        phe=request.POST.get('phone_a')
      # 方式一
      # user=models.User(name=name,password=pwd,address=addr)
      # user.save()   #寫入數(shù)據(jù)庫
        # 方式二
        models.User.objects.create(name=name,password=pwd,address=addr,phone=phe)

        return redirect('/user_list/')

def edit(request):
    if request.method=='GET':
        id=request.GET.get('id')
        # orm查詢單條數(shù)據(jù)
        user=models.User.objects.filter(id=id).first()
        return render(request,'edit.html',{'user':user})
    if request.method=='POST':
        id=request.POST.get("id")
        name = request.POST.get('name')
        pwd = request.POST.get('password')
        addr = request.POST.get('addr')
        phe = request.POST.get('phone_a')
        # orm的修改
        models.User.objects.filter(id=id).update(name=name,password=pwd,address=addr,phone=phe)
        return redirect('/user_list/')

4、在templates目錄中創(chuàng)建以下html文件

add.html

edit.html

user_list.html


add.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>新增用戶</title>
</head>
<body>
<form action="" method="post">
    <p>用戶名: <input type="text" name="name"></p>
    <p>密碼: <input type="password" name="password"></p>
    <p>地址: <input type="text" name="addr"></p>
    <p>電話:<input type="text" name="phone_a"></p>
    <input type="submit" value="提交">

</form>
</body>
</html>

edit.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/edit/?id={{ user.id }}" method="post">
    <p><input type="hidden" name="id" value="{{ user.id }}"></p>
    <p>用戶名: <input type="text" name="name" value="{{ user.name }}"></p>
    <p>密碼: <input type="text" name="password" value="{{ user.password }}"></p>
    <p>地址: <input type="text" name="addr" value="{{ user.address }}"></p>
    <p>電話:<input type="text" name="phone_a" value="{{ user.phone }}"></p>
    <input type="submit" value="提交">

</form>
</body>
</html>

user_list.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
<thead>
<tr>
    <th>id</th>
    <th>name</th>
    <th>password</th>
    <th>address</th>
    <th>phone</th>
    <th>delete</th>
    <th>add</th>
    <th>edit</th>
</tr>
</thead>
    <tbody>
        {% for user in user_list %}
            <tr>
                <td>{{ user.id }}</td>
                <td>{{ user.name }}</td>
                <td>{{ user.password }}</td>
                <td>{{ user.address }}</td>
                <td>{{ user.phone }}</td>
                <td><a href="/delete?id={{ user.id }}">刪除</a>    </td>
                <td><a href="/edit?id={{ user.id }}">編輯</a></td>
                <td><a href="/add/">新增用戶</a></td>
            </tr>
        {% endfor %}

    </tbody>
    </table>
</body>
</html>


總結(jié):

1 orm 創(chuàng)建表,新增字段,修改,刪除字段,不能創(chuàng)建數(shù)據(jù)庫
		-字段屬性phone=models.CharField(max_length=64,null=True)
		-null=True 代表該列可以為空
2 數(shù)據(jù)的增刪改查
		-增(1):User.objects.create(address='')
		-增(2):實例化產(chǎn)生一個user對象,user對象的save方法
		-刪:User.objects.filter(id=1,name='lqz').first().delete()
		-刪:User.objects.filter(id=1,name='lqz').delete()
		-改:User.objects.filter(id=1,name='lqz').update()
		-查:User.objects.all()
		    user=User.objects.filter(name='lqz')
			user.name
3 前后臺交互
-id=1&name='lqz'&
		<form action="/updateuser/?id={{ user.id }}" method="post">
			<p><input type="hidden" name="id" value="{{ user.id }}"></p>
			<p>用戶名: <input type="text" name="name" value="{{ user.name }}"></p>
			<p>密碼: <input type="text" name="password" value="{{ user.password }}"></p>
			<p>地址: <input type="text" name="addr" value="{{ user.address }}"></p>
			<input type="submit" value="提交">
		</form>
4 django生命周期		
	5 一對多,多對多
		-publish_id
		-publish=models.ForeignKey(to='Publish', to_field='id')
		book.publish_id
		book.publish
		多對多:(自動創(chuàng)建第三張表)
		authors = models.ManyToManyField(to='Author')





向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI