def get(self, request, id): profile = Profile.objects.filter(user=request.user)[0] book_info = requests.get( f'https://www.googleapis.com/books/v1/volumes/{id}').json() print(id) try: book = BookInfo.objects.get(google_id=id) except BookInfo.DoesNotExist: title = request.GET.get('title').replace("%20", " ") volume_info = book_info.get('volumeInfo') image_link = volume_info.get('imageLinks', {}).get('smallThumbnail', DEFAULT_BOOK_IMAGE_URL) book = BookInfo( google_id=id, title=title, authors=(",").join( volume_info.get('authors', ['Unknown author'])), description=volume_info.get('description', 'No description'), pageCount=volume_info.get('pageCount', ''), small_pic_url=image_link, ) book.save() shelf_name = request.GET.get('shelf').replace("%20", " ") shelf = profile.shelves.get(name=shelf_name) # here should be check for book on shelf, # actually it had to be before if book not in profile.books.all(): profile.books.add(book) profile_book_info = ProfileBookInfo() profile_book_info.profile = profile profile_book_info.shelf = shelf profile_book_info.book = book profile_book_info.time = datetime.now() # #profile=profile, book=book, time=datetime.now() # time_added.add(profile=profile) # profile_book_info.save() messages.success(request, f'Your book was added on {shelf_name} shelf!') else: messages.warning(request, f'Your already have this book on shelf') print(profile.bio) # return render(request, 'book/book_add.html', {'book': book_info}) return redirect('book_list')
def indexpage(request): ''' #F对象,求 readcount 小于id readcountlessOne = BookInfo.objects.filter(readcount__lt=F('id')) #Q对象 les = BookInfo.objects.filter(Q(id__gt=1) & Q(readcount__gt=50)) # 聚合函数 sum = BookInfo.objects.aggregate(Sum('readcount')) #排序 默认升序 BookInfo.objects.all().order_by('readcount') BookInfo.objects.all().order_by('-readcount') ''' # print(datetime.now()) # book = BookInfo.objects.all() # book.delete() book = BookInfo() books = BookInfo.objects.all() times = books.filter(pub_date__isnull=False).values("pub_date") time = [x['pub_date'].strftime('%Y-%m-%d ') for x in times] week = [ "Monday", "Tuesday", "Wednesday", "Thusday", "Friday", "Saturday", "Sunday" ] context = { "name": "tom", "books": books, "week": week, 'pub_date': time, } return render(request, "index.html", context)
def add_book_to_db(request, id): book_info = requests.get( f'https://www.googleapis.com/books/v1/volumes/{id}').json() try: book = BookInfo.objects.get(google_id=id) except BookInfo.DoesNotExist: volume_info = book_info.get('volumeInfo') image_link = volume_info.get('imageLinks', {}).get('smallThumbnail', DEFAULT_BOOK_IMAGE_URL) book = BookInfo( google_id=id, title=volume_info.get('title'), authors=(",").join(volume_info.get('authors', ['Unknown author'])), description=volume_info.get('description', 'No description'), pageCount=volume_info.get('pageCount', ''), small_pic_url=image_link, ) book.save() return redirect('book_detail', id=book.id)
def addData(request): BookInfo.objects.create(name="西游记", pub_date=datetime.strptime("2020-01-01", "%Y-%m-%d"), commentcount=20, readcount=32) BookInfo.objects.create(name="红楼梦", pub_date=datetime.strptime("2010-01-01", "%Y-%m-%d"), commentcount=24, readcount=50) BookInfo.objects.create(name="水浒传", pub_date=datetime.strptime("2001-01-01", "%Y-%m-%d"), commentcount=2, readcount=200) book = BookInfo(name='三国演义', pub_date=datetime.now(), commentcount=43, readcount=100) book.save() context = {'books': BookInfo.objects.all()} return render(request, 'index.html', context)
from django.test import TestCase # Create your tests here. # 插入数据 # 方式一: from book.models import BookInfo, PeopleInfo book = BookInfo(name='python入门', pub_date='2020-10-1') BookInfo.objects.create(name='python进阶', pub_date='2020-10-1', readcount=20, commentcount=10) book.save() # 方式二: PeopleInfo.objects.create(name='itheima', book=book) # 修改数据 # 方式一: person = PeopleInfo.objects.get(name='itheima') person.name = '小白' person.save() person # 方式二: books = BookInfo.objects.filter(name='python进阶').update(name='python高级') PeopleInfo.objects.create(name='小李', book=book) # 删除数据 # 方式一: person = PeopleInfo.objects.get(name='小李') person.delete() # 方式二: book = BookInfo.objects.get(name='python入门').delete()
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('ok') from book.models import BookInfo, PeopleInfo # 增加数据 book = BookInfo(name='itcast', pub_date='2010-4-5') book.save() # 方式2 book = BookInfo.objects.create(name='cast', ) # 修改 person = PeopleInfo.objects.get(name='黄药师') person.name = 'itcast' person.save() # 方式2 PeopleInfo.objects.filter(name='itcast').update(name='船只博客') # 删除 # 方式1物理删除 book = BookInfo.objects.get(id=6) book.delete() # 方式2 BookInfo.objects.filter(id=5).delete()
from django.shortcuts import render from django.http import HttpResponse # Create your views here. from book.models import BookInfo, PeopleInfo def index(request): return HttpResponse('ok') #################################新增数据 book = BookInfo(name='django', pub_date='2000-01-1', readcount=10) book.save() # 方式2 book1 = BookInfo.objects.create(name='django1', pub_date='2000-01-1', readcount=10) book1.save() #################################修改数据 # 方式一 book = BookInfo.objects.get(id=1) book.name = '射雕英雄传---1' book.save() # 方法二 BookInfo.objects.filter(id=8).update(name='爬虫', commentcount=666) # 删除数据 BookInfo.objects.get(id=8).delete()
from django.shortcuts import render from django.http import HttpResponse, HttpRequest from book.models import BookInfo from book.models import PeopleInfo ############################################################## 新增数据 ############################################################## # 方式一 book = BookInfo(name='python', pub_date='2020-01-01') # 需要手动调用save book.save() # 方式二 直接入库 # objects 模型的管理类 # 我们对模型的 增删改查 都找它 BookInfo.objects.create(name='java', pub_date='2020-05-29') ############################################################### 更新数据 ############################################################## # 方式1 # 1 先查询数据 book = BookInfo.objects.get(id=1) # 2 更新数据:直接修改实例属性 book.read_count = 20 # 3 调用save() book.save() # 方式二 直接更新 BookInfo.objects.filter(id=1).update(read_count=100, comment_count=200) ############################################################### 删除数据 ############################################################## # 方式1
# # 1.到数据库中查询书籍 # books = BookInfo.objects.all() # # 2.组织数据 # context = { # 'name': books, # } # # 3.传递给模板 # render(request,) # return HttpResponse('index') ####################################新增数据#################################### # python manage.py shell # 方式1 from book.models import BookInfo book = BookInfo(name='python', pub_date='2000-01-01') book.save() # 方式2 BookInfo.objects.create(name='java', pub_date='2021-5-10') ####################################更新数据#################################### # 方式1 # 1.查询数据 book = BookInfo.objects.get(id=1) # 2.修改属性 book.readcount = 20 # 3.保存 book.save() # 方式2 BookInfo.objects.filter(id=1).update(readcount=100, commentcount=100) #################################### filter \get \exclude ####################################
def index(request): return HttpResponse('ok') ######################z增加数据####################################### """ Model --> ORM --> 面向对象操作数据库 我们在进行增删改查的时候 就采用面向对象的操作 """ # 方式1 from book.models import BookInfo book = BookInfo(name='葵花宝典', pub_date='2020-1-2', readcount=100) # 必须调用 对象的save方法 数据才会保存到数据中 """ save方法的本质是 获取到对象的属性和属性值,调用ORM的数据保存方法 转换为一条sql语句,然后让mysql去执行 """ book.save() # 方式2 # 数据可以直接保存 # objects 相当于模型的管理属性 book = BookInfo.objects.create(name='django', pub_date='2005-1-1', readcount=666,
def upd_all_book(book_parser): """更新所有小说信息""" #global g_books #bt = time.time() for l in book_parser.book_list: l['Alias'] = l['Name'] + '_' + l['Author'] l['Alias_Host'] = l['Alias'] + '_' + book_parser.host_name l['Alias_Author'] = l['Author'] + '_' + book_parser.host_name l['is_new_book'] = config.Yes l['is_new_bookinfo'] = config.Yes l['is_new_contentinfo'] = config.Yes l['is_new_author'] = config.Yes for b in config.g_books: if (l['Alias'].decode(config.SYS_ENCODING)==b['Alias']): l['book_id'] = b['id'] l['is_new_book'] = config.No break if (l['is_new_book']): for a in config.g_authors: if (l['Alias_Author'].decode(config.SYS_ENCODING)==a['Alias']): #print l['Author'].decode(config.SYS_ENCODING), a['Name'] l['author_id'] = a['id'] l['is_new_author'] = config.No break for bi in config.g_bookinfos: if (l['Alias_Host'].decode(config.SYS_ENCODING)==bi['Alias']): l['bookinfo_id'] = bi['id'] l['is_new_bookinfo'] = config.No break #if (l.has_key('bookinfo_id')) and (config.g_contentinfos.has_key(l['bookinfo_id'])): try: if (config.g_contentinfos[l['bookinfo_id']] == l['Content_Url']): l['is_new_contentinfo'] = config.No #else: #config.g_contentinfos[l['bookinfo_id']] = l['Content_Url'] except KeyError: pass #print "step 1 use time: %f" % (time.time()-bt) #bt = time.time() k = 0 for b in book_parser.book_list: if (book_parser.is_origin): if (b.has_key('is_new_book') and (b['is_new_book'])): if (b.has_key('is_new_author') and (b['is_new_author'])): author = Author() author.Name = b['Author'].decode(config.SYS_ENCODING) author.Alias = b['Alias_Author'].decode(config.SYS_ENCODING) author.save() b['author_id'] = author.id config.g_authors.append(model_to_dict(author)) book = Book() book.Name = b['Name'].decode(config.SYS_ENCODING) book.Alias = b['Alias'].decode(config.SYS_ENCODING) book.author_id = b['author_id'] book.save() config.g_books.append(model_to_dict(book)) b['book_id'] = book.id b['is_new_book'] = config.No b['is_new_author'] = config.No if (b.has_key('is_new_bookinfo') and b.has_key('is_new_book')): if ((b['is_new_bookinfo']) and (not b['is_new_book'])): bookinfo = BookInfo() bookinfo.book_id = b['book_id'] bookinfo.HostName = book_parser.host_name bookinfo.BookUrl = b['Book_Url'] bookinfo.Alias = b['Alias_Host'].decode(config.SYS_ENCODING) bookinfo.LastContent = b['Content'].decode(config.SYS_ENCODING) bookinfo.ContentUrl = b['Content_Url'] bookinfo.LastUpdated = time.time() bookinfo.save() config.g_bookinfos.append(model_to_dict(bookinfo)) b['bookinfo_id'] = bookinfo.id b['is_new_bookinfo'] = config.No """ else: bookinfo = BookInfo.objects.get(id=b['bookinfo_id']) bookinfo.LastContent = b['Content'].decode(config.SYS_ENCODING) bookinfo.ContentUrl = b['Content_Url'] bookinfo.LastUpdated = time.strftime('%Y-%m-%d %H:%M', time.localtime()) bookinfo.save() """ if (b.has_key('is_new_contentinfo') and b.has_key('is_new_book')): if ((b['is_new_contentinfo']) and (not b['is_new_book'])): k = k + 1 cinfo = ContentInfo() cinfo.bookinfo_id = b['bookinfo_id'] cinfo.LastContent = b['Content'].decode(config.SYS_ENCODING) cinfo.ContentUrl = b['Content_Url'] cinfo.LastUpdated = time.strftime('%Y-%m-%d %H:%M', time.localtime()) cinfo.save() config.g_contentinfos[b['bookinfo_id']] = b['Content_Url'] b['is_new_contentinfo'] = config.No
def aaaa(request): ######增加数据######### from book.models import BookInfo book = BookInfo(name='水浒传') book book = BookInfo.objects.create(name='三国演义') #############修改数据######### #第一种方式 #先获取到数据,然后再修改数据的字段 book.readcount = 100 #注意调用save方法 book.save() #第二种修改数据的方式 BookInfo.objects.filter(id=6).update(commentcount=200) #################删除数据############### #第一种方法 book.delete() #第二种方法 BookInfo.objects.filter(id=5).delete() ########查询########## #get查询单一结果,如果不存在抛出模型类,异常 book = BookInfo.objects.get(id=1) book = BookInfo.objects.get(pk=1) #primary #DoesNotExist不存在的异常 book = BookInfo.objects.get(id=10) #all查询所有 book = BookInfo.objects.all() #count查询数量 count = BookInfo.objects.all().count() #where #filter过滤出多个结果,一个或者0个 # exclude排除符合条件的剩下的结果 相当于not #get单一的结果 #以filter为例子说明一下语法形式 #filter(字段名__运算符=值) # 查询编号为1的图书 book = BookInfo.objects.get(id__exact=1) book = BookInfo.objects.get(id=1) book = BookInfo.objects.get(pk=1) #返回的结果是列表,如果需要拿到数据需要遍历 book = BookInfo.objects.filter(pk=1) # 查询书名包含'湖'的图书 books = BookInfo.objects.filter(name__contains='湖') # 查询书名以'部'结尾的图书 books = BookInfo.objects.filter(name__endswith='湖') # 查询书名为空的图书 books = BookInfo.objects.filter(name__isnull=True) books = BookInfo.objects.filter(pub_date__isnull=True) # 查询编号为1或3或5的图书 books = BookInfo.objects.filter(id_in=(1, 3)) # 查询编号大于3的图书 # gt 大于 #gte大于等于 #lt小于 #lte小于等于 books = BookInfo.objects.filter(id_gt=3) #查询编号不等于3的书籍 books = BookInfo.objects.exclude(id=3) # 查询1980年发表的图书 books = BookInfo.objects.filter(pub_date__year='2018') # 查询1990年1月1日后发表的图书 books = BookInfo.objects.filter(pub_date__gt='1990-1-1') #查询评论数大于阅读数量的书籍 from django.db.models import F #F(‘字段’) #只需要把常量值换成F books = BookInfo.objects.filter(commentcount__gt=F('readcount')) #查询评论数大于阅读数量2倍的书籍 books = BookInfo.objects.filter(commentcount__gt=F('readcount') * 2) #多个逻辑关系 #查询阅读数量大于30并且id>3的书籍 #第一种写法 books = BookInfo.objects.filter(readcount__gt=30, id__gt=3) #第二种写法 books = BookInfo.objects.filter(readcount__gt=30).filter(id__gt=3) # Q对象就是相当于or #语法形式Q(字段__运算符=值)| Q(字段__运算符=值) from django.db.models import Q book = BookInfo.objects.filter(Q(readcount__gt=30) | Q(id__gt=3)) #查询id不等于3的 #还可以使用~Q查询 books = BookInfo.objects.filter(~Q(id=3)) #聚合函数 #aggregate 和 聚合函数Avg Sum Man Min Count配合使用 from django.db.models import Sum, Max, Min, Avg, Count book = BookInfo.objects.aggregate(Sum('readcount')) #order_by(字段) #默认升序 book = BookInfo.objects.all().order_by('id') #降序 book = BookInfo.objects.all().order_by('-id') #多个字段排序的原理是第一个字段的值相等,按着第二个字段排序 books = BookInfo.objects.all().order_by('readcount', 'commentcount') #关联查询 # 查询书籍为1的所有人物信息 #先找到书籍为1的书,再通过书查到任务信息 books = BookInfo.objects.get(id=1) people = books.peopleinfo_set.all() # 查询人物为1的书籍信息 #先查询人物再查寻书记 from book.models import PeopleInfo person = PeopleInfo.objects.get(id=1) person.book.name #关联查询的筛选 # 查询图书,要求图书人物为 "郭靖" 一对多的查询 #先查询出图书,再查出图书中名字为郭靖的人 book = BookInfo.objects.filter(peopleinfo__name='郭靖') # 查询图书,要求图书中人物的描述包含 "八" book = BookInfo.objects.filter(peopleinfo__description__contains='八') #多对一 # 查询书名为“天龙八部”的所有人物 people = PeopleInfo.objects.filter(book__name='天龙八部') # 查询图书阅读量大于30的所有人物 people = PeopleInfo.objects.filter(book__readcount__gt=30) # filter order_by , exclude all #他们都是chacun结果,可以理解为对象列表 books = BookInfo.objects.all() #缓存就是将数据放置到一个地方(本地) # [book.id for book in BookInfo.objects.all()] # limit offset page #限制查询结果集 books = BookInfo.objects.all()[0:2] return HttpResponse('ok')
# # from book.models import BookInfo # book = BookInfo.objects.all(id__in=(1,2)) # # def index(request): # # 准备上下文:定义在字典中的()测试数据 # context = {"title":"测试模板处理数据"} # # # 江上下文交给模板中进行处理,处理后视图响应给客户端 # return render(request, 'book/index.html',context) ######################数据的添加########################### # 方法一 from book.models import BookInfo, PeopleInfo book = BookInfo(name='python入门', pub_date='2010-1-1') book.save() # 像事件的提交 # 方法二 PeopleInfo.objects.create(name="itheima", book=book) ########################数据的修改######################### # 方法一 person = PeopleInfo.objects.get(name="itheima") person.name = "itcast" person.save() # 方法二 PeopleInfo.objects.filter(name="itcast").update(name="传智博客") # 会返回影响的行数
from book.models import BookInfo,PeopleInfo # Create your views here. def index(request): # here add insert/delete/update/select books = BookInfo.objects.all() print(books) return HttpResponse('index') # insert data method 1 book=BookInfo( name='Django', pub_date='1931-4-24', readcount=0, commentcount=0, is_delete=0 ) book.save() # insert data method 2 BookInfo.objects.create( name='Django2', pub_date='1931-4-25', readcount=0, commentcount=0, is_delete=0 )
# Create your views here. from book.models import BookInfo def index(resquest): # 在这里实现 增删改查 books = BookInfo.objects.all() print(books) return HttpResponse("index") # ############################增加数据############################## # 方式1 book = BookInfo( name='Django', pub_date='2020-1-1', readcount=100, ) book.save() # 必须调用对象的方法 save()将数据保存到数据库 # 方式2 # object -- 相当于一个代理 实现增删改查 BookInfo.objects.create(name='测试开发入门', pub_date='2020-1-1', readcount=100) # ############################修改数据############################## # 方法1 select * from bookinfo where id =6; book = BookInfo.objects.get(id=6) book.name = '运维入门方法' book.commentcount = 666 book.save()
# 3.传递给模板进行渲染 return render(request, 'index.html', context=context) # books return HttpResponse('ok') ##########################增删改######################################### # 增加数据 2种方式 # 第一种方式 from book.models import BookInfo book = BookInfo(name='python入门', pub_date='2000-1-1', readcount=20) # book.commentcount = 100 # 这种方式我们需要手动调用 save方法进行保存 book.save() # 第二种,直接保存 """ 在命令行输入下面代码,返回的便是book BookInfo.objects.create( name='java1', pub_date='2010-1-1', readcount=100 ) """
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('ok') from book.models import BookInfo, PeopleInfo # BookInfo.objects.all() # from book.models import BookInfo,PeopleInfo from book.models import BookInfo book = BookInfo(name='葵花宝典', pub_date='2020-1-2', readcount=100) # 必须调用 对象的save方法 数据才会保存到数据中 """ save方法的本质是 获取到对象的属性和属性值,调用ORM的数据保存方法 转换为一条sql语句,然后让mysql去执行 """ # book.save() # 方式2 # 数据可以直接保存 # objects 相当于模型的管理属性 book = BookInfo.objects.create(name='django', pub_date='2005-1-1', readcount=666, commentcount=999)
books = BookInfo.objects.all() # books = [BookInfo.objects.all()] context = {'books': books} # render # 参数1:当前的请求 # 参数2:模板文件 # 参数3:context传递参数 return render(request, 'index.html', context=context) # return HttpResponse('index') ################################新增数据################################# # 方式1 book = BookInfo(name='python', ) # 需要手动调用save方法 book.save() # 方式2 直接入库 # object 模型的管理类 # 我们对模型的 增删改查 都找它 BookInfo.objects.create(name='java', pub_date='2010-2-1') ###############################修改(更新)数据#################################### from book.models import BookInfo # 方式1 # 1.先查询数据
from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return HttpResponse('index') from book.models import BookInfo book=BookInfo(name='Django', pub_date='2000-1-1', readcount=10 ) book.save() BookInfo.objects.create(name='Django', pub_date='2000-1-1', readcount=10) book=BookInfo.objects.get(id=6) book.name='运维开发入门' book.save() BookInfo.objects.filter(id=6).update(name='爬虫入门',commentcount=6) book=BookInfo.objects.get(id=6) book.delete() BookInfo.objects.filter(id=5).delete()
def index(request): # return HttpResponse("index") # 模拟数据查询 context = {"name": "用户登录"} return render(request, 'book/index.html', context=context) from book.models import BookInfo from book.models import PeopleInfo ##################添加数据#################### # 方式1 book = BookInfo(name="django", pub_time="2020-1-1", readcount=10) # 必须要调用对象的save方法才能将对象的数据保存到数据库 book.save() # 方式2 # objects --> 相当于一个代理 实现增删改查 BookInfo.objects.create(name="HTML入门", pub_time="2008-3-13", readcount=133, commentcount=1200) ##################修改数据#################### # 方式1 # select * from bookinfo where id=1 book = BookInfo.objects.get(id=1)