django-ORM单表操作
生活随笔
收集整理的這篇文章主要介紹了
django-ORM单表操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、ORM與數據庫的關系
| 類 | 表 | ? |
| 類屬性 | 表字段 | ? |
| 對象 | 表記錄 | ? |
2、
class Books(models.Model):nid = models.AutoField(primary_key=True)title = models.CharField(max_length=32)price = models.DecimalField(max_digits=8, decimal_places=2) # 最大值: 999999.99pub_date = models.DateTimeField() # django 要求必須存這種格式:2019-07-12publish = models.CharField(max_length=32)執行數據庫遷移命令,生成表:(在這之前請確保settings中配置了數據庫連接,比如mysql,以及存在相應的database)
3、
4、ORM單表操作
4.1 增加數據
# 增 ## 方式一: book = Book(title="python", price=123, pub_date="2019-9-22", publish="人民出版社") book.save()## 方式二:推薦 book = Book.objects.create(title="python", price=123, pub_date="2019-9-22", publish="人民出版社") print(book.title) ########### 添加書籍完整代碼 ############ def addbook(request): # get請求拿數據,post請求提交數據if request.method == "POST":title = request.POST.get('title')price = request.POST.get('price')pub_date = request.POST.get('pub_date')publish = request.POST.get('publish')Books.objects.create(title=title, price=price, pub_date=pub_date, publish=publish)return redirect(reverse("books"))else: # get請求,請求的是添加書籍的表單頁面,返回addbook.html頁面給用戶return render(request, "addbook.html", locals())展示頁面
<!-- 書籍顯示:完整的前端代碼 --> <!-- 書籍添加:完整的前端代碼 --> <h3>添加書籍</h3> <div class="container"><div class="row"><div class="col-md-8 col-md-offset-2"><!--action在此處硬編碼了,也可以利用反向解析實現:action="{% url 'addbook' %}"--><form action="/books/add/" method="post"> <!-- action 可以什么都不寫,默認發到當前頁面 -->{% csrf_token %}<div class="form-group"><label for="title">書籍名稱</label><input type="text" class="form-control" id="title" placeholder="Title" name="title"></div><div class="form-group"><label for="price">價格</label><input type="text" class="form-control" id="price" placeholder="Price" name="price"></div><div class="form-group"><label for="pub_date">出版日期</label><input type="date" class="form-control" id="pub_date" placeholder="pub_date" name="pub_date"></div><div class="form-group"><label for="publish">出版社</label><input type="text" class="form-control" id="publish" placeholder="publish" name="publish"></div><button type="submit" class="btn btn-success pull-right">Submit</button></form></div></div> </div>4.2 查詢數據
# 查 -- 用的最多,最繁瑣的 ## 查詢所有,結果為QuerySet(特殊的列表),可以for循環,可以切片 取數據 book_list = Book.objects.all() # <QuerySet [<Books: Books object (1)>, <Books: Books object (2)>]> ## 條件查詢 book_list= Book.objects.filter(price=100) # 返回的結果也是 QuerySet################# 完整的后端代碼 ################# def books(request):# 查詢所有book_list = Books.objects.all()return render(request, "books.html", {"book_list": book_list})展示數據
<!-- 書籍顯示:完整的前端代碼 --> <h3>書籍列表</h3> <div class="container"><div class="row"><div class="col-md-8 col-md-offset-2"><a href="/books/add/" class="btn btn-primary">添加書籍</a><table class="table table-striped table-hover"> <!-- striped為斑馬線,hover為懸浮效果--><thead><tr><th>編號</th><th>書籍名稱</th><th>價格</th><th>出版日期</th><th>出版社</th><th>操作</th></tr></thead><tbody>{% for book in book_list %}<tr><td>{{ book.nid }}</td><td>{{ book.title }}</td><td>{{ book.price }}</td><td>{{ book.pub_date|date:'Y-m-d'}}</td><td>{{ book.publish }}</td><td><a href="/books/edit/{{ book.nid }}" class="btn btn-warning btn-sm">編輯</a><!--href這里也是硬編碼了,可以寫成:href="{% url 'editbook' book.nid %}"--><!-- 如果有多個動態參數,用空格隔開即可 --><a href="/books/delete/{{ book.nid }}/" class="btn btn-danger btn-sm">刪除</a></td></tr>{% endfor %}</tbody></table></div></div> </div>4.3 刪除數據
# 刪 -- 想刪誰,要先查出來,要用到查詢 Book.objects.filter(nid=3).delete() # 先找到要刪除的結果(QuerySet),直接刪除 Book.objects.get(nid=7).delete() # model對象,找到自己,然后刪除 ####### 完整的后端代碼 ######## def delbooks(request, delete_book_id):Books.objects.filter(nid=delete_book_id).delete()return redirect(reverse("books"))4.4 修改數據
# 改,與刪的語法都很簡單,關鍵點在于查,怎么能夠將要操作的記錄給查出來,語法如下 Books.objects.filter(nid=edit_book_id).update(price=120) # http://127.0.0.1:8000/edit/9 就直接修改掉了 Books.objects.filter(price=111).update(publish="南京出版社") return redirect("/books/") ############## 完整代碼 ################ def editbooks(request, edit_book_id):if request.method == "GET":edit_book = Books.objects.filter(nid=edit_book_id)[0]return render(request, "editbook.html", {"edit_book": edit_book})else:title = request.POST.get('title')price = request.POST.get('price')pub_date = request.POST.get('pub_date')publish = request.POST.get('publish')Books.objects.filter(nid=edit_book_id).update(title=title, price=price, pub_date=pub_date, publish=publish)return redirect(reverse("books"))展示數據
<!-- 書籍編輯:完整的前端代碼 --> <a href="#">編輯書籍</a> <div class="container"><div class="row"><div class="col-md-8 col-md-offset-2"><form action="" method="post"> <!-- action 可以什么都不寫,默認發到當前頁面 /books/edit/{{ edit_book.nid }} -->{% csrf_token %}<div class="form-group"><label for="title">書籍名稱</label><input type="text" value="{{ edit_book.title }}" class="form-control" id="title" placeholder="Title" name="title"></div><div class="form-group"><label for="price">價格</label><input type="text" value="{{ edit_book.price }}" class="form-control" id="price" placeholder="Price" name="price"></div><div class="form-group"><label for="pub_date">出版日期</label><input type="date" value="{{ edit_book.pub_date|date:'Y-m-d'}}" class="form-control" id="pub_date" placeholder="pub_date" name="pub_date"></div><div class="form-group"><label for="publish">出版社</label><input type="text" value="{{ edit_book.publish }}" class="form-control" id="publish" placeholder="publish" name="publish"></div><button type="submit" class="btn btn-success pull-right">Submit</button></form></div></div> </div>5、
<!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style>.container {margin-top: 65px;} </style>6、
from django.contrib import admin from django.urls import path, re_path from book import viewsurlpatterns = [path('admin/', admin.site.urls),path('books/add/', views.addbook, name='addbook'),re_path('books/delete/(\d+)/', views.delbooks, name='delbooks'),re_path('books/edit/(\d+)/', views.editbooks, name='editbooks'),path('books/', views.books, name='books'),path('index/', views.index, name='index'), ]7、
filter() 帶條件查詢
get() 查詢結果只有一個,超過一個或沒有都會報錯(應用場景:)
exclude() 查詢與所給條件不匹配的對象
order_by() 對查詢結果排序
reverse() 對查詢結果倒序
count() 返回匹配結果的個數
first() 返回第一條記錄
last() 返回最后一條記錄
exists() 如果QuerySet包含數據返回True,否則返回False,bool值
values() 返回一個特殊的Queryset,運行后得到的并不是一列model實例化對象,而是一個可迭代的字典序列
values_list() 與values相似,返回的是一個元組序列,values返回的是一個字典序列
distinct() 對查詢結果去重
Book.objects.filter(price__in=[100,200,300]) Book.objects.filter(price__gt=100) Book.objects.filter(price__gte=100) Book.objects.filter(price__lt=100) Book.objects.filter(price__range=[100,200]) Book.objects.filter(title__contains="python") Book.objects.filter(title__icontains="python") Book.objects.filter(title__startswith="py") Book.objects.filter(pub_date__year=2012)
?
轉載于:https://www.cnblogs.com/miaocbin/p/11311438.html
總結
以上是生活随笔為你收集整理的django-ORM单表操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: XML指南——XML 确认
- 下一篇: HZOJ 矩阵游戏