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 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.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(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() # 方法2 select * from bookinfo where id =6; BookInfo.objects.filter(id=5).update(name='python入门方法', commentcount=999)
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="传智博客") # 会返回影响的行数 ##########################数据的删除######################