其他分享
首页 > 其他分享> > Django框架之queryset数据类型

Django框架之queryset数据类型

作者:互联网

 

from django.shortcuts import render,HttpResponse
from book.models import Book
import datetime
# Create your views here.
def add_book(request):

#添加书籍
# 方式1
#date = datetime.date(year=2012,month=12,day=12)
#book = Book(title="xiyouji", price=199, pub_date=date)
book = Book(title="xiyouji",price=199,pub_date="2012-12-12")
print(book.id) #None
book.save() #执行sql
print(book.id) # 3

# 方式2
book = Book.objects.create(title="sanguoyanyi",price=299,pub_date="2011-11-11")
print(book.id)
print(book.price)

def select_book(request):
# (1) 查询所有的书籍,返回值是一个queryset类型对象
book_list= Book.objects.all()
'''
ORM数据引擎:

select id, title, price, pub_date from book:
+------+--------------+---------+------------+
id title price pub_date
+------+--------------+---------+------------+
1 西游记 499.00 2011-12-12
2 三国演义 399.00 2019-06-12
3 水浒传 299.00 2008-06-12
4 红楼梦 199.00 2020-06-12
+------+--------------+---------+------------+
book01 = Book(1 | 西游记 |499.00 |2011-12-12)
book02 = Book(2 | 三国演义 |399.00 |2019-06-12)
book03 = Book(3 | 水浒传 |299.00 |2008-06-12)
book04 = Book(4 | 红楼梦 |199.00 |2020-06-12)

book_list = queryset[book01,book02,book03,book04]

'''
print ("book_list",book_list) # <QuerySet [<Book: Book object (1)>,...]

#QuerySet:支持索引操作,支持遍历
book = book_list[0]
print(book.id) # 1
print(book.title) # 西游记
print(book.price) # 499.00
# print(book_list.title)
for book in book_list:
print (book.id,book.title) #1 西游记 2 三国演义 3 水浒传 4 红楼梦

return HttpResponse("添加书籍")

标签:12,title,Book,数据类型,queryset,Django,date,book,print
来源: https://www.cnblogs.com/A121/p/16459387.html