ORM操作:
管理器对象:
创建数据:
Django shell
想要操作模型对象,首先我们需要把它引进Django shell中
>>> from bookstore.models import Book
>>> b1 = Book.objects.create(title='AI', pub='清华大学出版社', price= 20,market_price = 25)
>>> b2 = Book(title='爱',pub='清华大学出版社',price=70,market_price = 50)
>>> b2.save()
查询数据:
例子:
第一步:在django学习下的settings中添加bookstore
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 'music',
# 'news',
# 'sport',
'bookstore'
]
第二步:在 django学习下的urls添加bookstore
from django.contrib import admin
from django.urls import path,include,re_path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
# 主路由链接需要加/
#path('music/',include("music.urls")),
#path('sport/',include("sport.urls")),
#path('news/',include("news.urls")),
path('bookstore/',include('bookstore.urls'))
]
第三步:在bookstore的模型和视图以及url
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('all_book', views.all_books, name='all_book')
]
views.py:
from django.shortcuts import render
from bookstore.models import Book
# Create your views here.
def all_books(request):
books = Book.objects.all()
return render(request, 'bookstore/all_book.html',locals())
all_book.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查看所有书籍</title>
</head>
<body>
<table >
<tr>
<th>id</th>
<th>title</th>
<th>pub</th>
<th>price</th>
<th>market_price</th>
<th>op</th>
</tr>
{% for book in books %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.title }}</td>
<td>{{ book.pub }}</td>
<td>{{ book.price }}</td>
<td>{{ book.market_price }}</td>
<td>
<a href="">删除</a>
<a href="">更新</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
条件查询:
查询谓词:
修改数据:
删除操作:
单个删除:
批量删除:
伪删除: