第二篇-Django建立数据库各表之间的联系(中)

上篇中已经建立了两个table,Book和Publish。这篇介绍如何用python增删改查数据库中的数据。

在views.py中创建一个index函数

from django.shortcuts import render

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

def index(request):
    return render(request,"index.html")

 返回一个index.html页面。urls.py中也要加入相应的函数。

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

 写一个index.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .head{
            line-height: 40px;
            background-color: green;
            color: white;
            text-align: center;
        }
    </style>
</head>
<body>

<div class="outer">
    <div class="head">标题</div>
    <h1>一对多</h1>
    <div class="content">
        <a href="/addbook/">添加书籍</a>
        <a href="/update/">修改书籍</a>
        <a href="/delete/">删除书籍</a>
        <a href="/select/">查询书籍</a>
    </div>
    <hr>
    <div class="queryResult">
        {% for book in book_list %}
            <div>
                <p>{{ book.name }} {{ book.author }} {{ book.price }}</p>
            </div>
        {% endfor %}
    </div>
</div>

</body>
</html>

 由于html中点击添加书籍,修改书籍,删除书籍以及查询书籍会跳到不同的链接,所以在urls.py里面要添加相应链接

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('addbook/', views.addbook),
    path('update/', views.update),
    path('delete/', views.delete),
    path('select/', views.select),
]

 同样,在views.py中要添加相应函数,先写一个addbook的函数进行测试。

from django.shortcuts import render,HttpResponse

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

def index(request):
    return render(request,"index.html")

def addbook(request):
    Book.objects.create(name="linux运维",price=77,pub_date="2018-11-2",publish_id=2)
    return HttpResponse("添加成功")

def update():pass

def delete():pass

def select():pass
View Code

然后可以运行试试,在命令行窗口Terminal中使用命令:

python manage.py runserver 8888

然后在浏览器地址栏输入http://127.0.0.1:8888/index/

 

得到此页面,由于我们已经在views.py中写了addbook的函数,所以我们可以点击添加书籍,看看有没有把书籍添加进去。会跳进addbook界面。

我们现在在去数据库中查看,会发现已经添加了一行信息进去

id那一栏是自动按照自增一的顺序添加的,由于第一次添加数据时,由于没有建立publish表,导致外键不能添加报错。所以id=1已经被使用了,后来建立的id是从2开始的。可以看到linux运维这一栏已经被添加成功了。

注意,之前添加外键那一栏的时候是直接用 publish_id添加的,如果想用publish添加的话,需要用对象添加进去。

def addbook(request):
    # Book.objects.create(name="linux运维",price=77,pub_date="2018-11-2",publish_id=2)

    publish_obj=Publish.objects.filter(name="人民出版社")[0]
    Book.objects.create(name="GO",price=23,pub_date="2018-10-2",publish=publish_obj)
    return HttpResponse("添加成功")
View Code

刷新http://127.0.0.1:8888/addbook/,可以看见GO那一栏也被添加进去了。

 

posted @ 2018-11-02 09:30  o云淡风轻o  阅读(340)  评论(0编辑  收藏  举报