def populate(): print('Populating books...', end='') titles = [ '穿在身上的 --草地恐龍時代毛衣', '穿在身上的 --星空刺繡暴龍長袖T恤', '穿在身上的 --手繪躲貓貓長袖T恤', '穿在身上的 --刺繡小鹿坑條毛衣', '穿在腿上的 --前口袋棉麻寬褲 ( 灰綠色 / 深灰色 )', '穿在腿上的 --刺繡扣復古高腰七分裙 ( 灰 / 藍 )', '其他其他的小東西 --窗台上的祕密戒指', '其他其他的小東西 --解不開結的戒指', '其他其他的小東西 --窗台的祕密戒指', '其他其他的小東西 --諾亞之心戒指', '裝錢的錢包 --水松木長夾( 彩色 / 原色 )', '裝錢的錢包 --手染掛頸手機零錢收納包 ( 海洋 / 夕陽 / 沙漠 )', ] materials = ['棉麻', 'Cotton, Polyester', 'Portuguese Cork', '銀'] Book.objects.all().delete() for title in titles: book = Book() book.title = title n = random.randint(0, len(materials) - 1) book.material = materials[n] book.pubdate = datetime.datetime.today() book.price = 690 book.save() print('done')
def index(request): ''' 操作rom 1.所有的模型类都有个objects属性,就是一个manager对象,用于进行数据操作管理 2.添加数据 2.1 模型类。objects.create(属性=值) 返回生成的对象----》记录 2.2 添加数据 对象 = 模型类() 对象。属性=值 对象。save()保存数据 2.3 ,模型类。objects.get_or_crate(属性=值) 如果有就获取,没有就创造 3查看数据 模型类。objects.all() 查看所有数据 模型类。objects.filter(条件)条件查询,相当于where 模型类。objects.get(条件)只能获取一条数据 4修改数据 4.1 模型类。object。filter(条件).update(属性=新属性值) 一次更新多条 4.2 先查询出对象 ---一次更新一条 对象。属性=值 对象。属性=值 对象。属性=值 对象。save() 5 删除数据 查询偶delete() :param request: :return: ''' rs = Book.objects.create(name='红楼梦', author='曹雪芹', price=9.9) print(rs) book = Book() book.name = '红楼梦' book.author = '曹雪芹' book.price = 99 book.save() book = Book.objects.get_or_create(name='三国演义', author='施耐庵', price=88) print(book) #查看数据 # books=Book.objects.all() # content = { # "books":books # } # book = Book.objects.get(id=1) # book = Book.objects.get(name='红楼梦') 如果存在多条数据,返回列表[] # books = Book.objects.filter(name='红楼梦').first()#获取第一条 # print(book) #更新数据 # rs = Book.objects.filter(name='红楼梦').update(name='红楼2') # print(rs) # book = Book.objects.get(id=1) # book.name='红楼3' # book.save() book = Book.objects.get(id=1) book.delete() return HttpResponse("bookModel")
def add_book(request): context = dict() if request.method == "POST": if "url" in request.POST: url = request.POST["url"] context = parse_book_by_isbn(url) return render(request, "book/add.html", context) if "isbn" in request.POST: isbn = request.POST["isbn"] context = parse_book_by_isbn(isbn) book = Book() book.title = context["title"] book.publisher = context["publisher"] book.isbn = context["isbn"] book.url = context["url"] book.ispersonal = int(True) book.ownerid = request.user.id book.summary = context["summary"] book.price = context["price"] book.numraters = 0 book.averageRate = 3 book.created_date = datetime.datetime.now() book.updated_date = datetime.datetime.now() book.author = context["author"][0] book.authorinfo = context["author_intro"][0:4090] # print book.authorinfo book.catelog = context["catalog"][0:4090] book.pubdate = context["pubdate"] book.ispublic = int(True) book.imgurl = context["images"] book.city = Dper.objects.get(user_id=request.user.id).city book.bookcount = 1 book.status = 1 # Dper.objects.filter(id=request.user.id)[0].city book.save() # save tags of book for val in context["tags"]: tag = Tag() tag.value = val tag.createdate = datetime.datetime.now() tag.save() rel = Booktag() rel.tagid = tag.id rel.bookid = book.id rel.save() return redirect("/book/library", context) else: form = BookForm() context["form"] = form return render(request, "book/add.html", context)
def populate(): print('Populating bkName ... ', end='') Book.objects.all().delete() i = 1 for bkName in bkNames: book = Book() book.bkName = bkName book.authorName = 'at' + str(i) book.publisher = 'pub' + str(i) book.pubversion = 1 book.price = i * 100 book.inventory = 10 i += 1 book.save() print('done')
def book_add(request): response_data = {} response_data['result'] = 'error' # Requests req = json.loads(request.body.decode('utf-8')) book_item = Book() book_item.isbn = req['isbn'] book_item.title = req['title'] book_item.author = req['author'] book_item.translator = req['translator'] book_item.edition = req['edition'] book_item.pubhouse = req['pubhouse'] book_item.pubtime = req['pubtime'] book_item.summary = req['summary'] book_item.context = req['context'] book_item.clc = req['clc'] book_item.price = req['price'] # add cate book_item.save() for item in req['category']: try: # print(item['id']) cate = Category.objects.get(id=item['id']) book_item.category.add(cate) except: pass # add tag for item in req['tag']: try: tag = Tag.objects.get(id=item['id']) book_item.tag.add(tag) except: pass # Save book try: book_item.save() # Response Data response_data['result'] = 'ok' response_data['book_id'] = book_item.bookid except: response_data['message'] = 'Fail to save data.' return JsonResponse(response_data)
def add_book(request): context = dict() if request.method == 'POST': if 'url' in request.POST: url = request.POST['url'] context = parse_book_by_url(url) return render(request, 'book/add.html', context) if 'bookid' in request.POST: bookid = request.POST['bookid'] context = parse_book_by_id(bookid) book = Book() book.title = context['title'] book.publisher = context['publisher'] book.isbn = context['isbn10'] if 'isbn10' in context else context[ 'isbn13'] book.url = context['url'] book.ispersonal = int(True) book.ownerid = request.user.id book.summary = context['summary'] book.price = context['price'] book.numraters = 0 book.averageRate = 3 book.created_date = datetime.datetime.now() book.updated_date = datetime.datetime.now() book.author = context['author'][0] book.pubdate = context['pubdate'] book.ispublic = int(True) book.imgurl = context['images'] book.save() #save tags of book for val in context['tags']: tag = Tag() tag.value = val tag.createdate = datetime.datetime.now() tag.save() rel = Booktag() rel.tagid = tag.id rel.bookid = book.id rel.save() return redirect('/book/library', context) else: form = BookForm() context['form'] = form return render(request, 'book/add.html', context)
def populate(): print('Populating Book...', end='') titles = [ 'python', '小王子', 'Java', '黑子的籃球', 'Django', '管理數學', '計概', 'c++', 'vb', '少年陰陽師' ] authornames = ['王一', '王二', '王三'] Book.objects.all().delete() for title in titles: book = Book() book.title = title book.authorname = authornames[random.randint(0, len(authornames) - 1)] book.publisher = book.authorname book.date = datetime.datetime.today() book.version = '1' book.price = 1000 book.save() print('done')
def add_book(request): context = dict() if request.method == 'POST': if 'url' in request.POST: url = request.POST['url'] context = parse_book_by_url(url) return render(request, 'book/add.html', context) if 'bookid' in request.POST: bookid = request.POST['bookid'] context = parse_book_by_id(bookid) book = Book() book.title = context['title'] book.publisher = context['publisher'] book.isbn = context['isbn10'] if 'isbn10' in context else context['isbn13'] book.url = context['url'] book.ispersonal = int(True) book.ownerid = request.user.id book.summary = context['summary'] book.price = context['price'] book.numraters = 0 book.averageRate = 3 book.created_date = datetime.datetime.now() book.updated_date = datetime.datetime.now() book.author = context['author'][0] book.pubdate = context['pubdate'] book.ispublic = int(True) book.imgurl = context['images'] book.save() #save tags of book for val in context['tags']: tag = Tag() tag.value = val tag.createdate = datetime.datetime.now() tag.save() rel = Booktag() rel.tagid = tag.id rel.bookid = book.id rel.save() return redirect('/book/library', context) else: form = BookForm() context['form'] = form return render(request, 'book/add.html', context)
def populate(): print('Populating articles and comments ... ', end='') Book.objects.all().delete() Review.objects.all().delete() for title, content in zip(titles, contents): book = Book() book.title = title book.content = content book.author = authors book.publisher = publishers book.publicationDate = publicationDate book.price = 999 book.save() for review, score in zip(reviews, scores): Review.objects.create(book=book, review=review, score=score) print('done')
def populate(): print('Populating book...', end='') titles = ['如何像電腦科學家一樣思考', '10 分鐘內學好 Python', '簡單學習 Django' '如何像電腦科學家一樣思考2', '10 分鐘內學好 Python2', '簡單學習 Django2' '如何像電腦科學家一樣思考3', '10 分鐘內學好 Python3', '簡單學習 Django3' '如何像電腦科學家一樣思考4', '10 分鐘內學好 Python4', '簡單學習 Django4'] authors =['張三','李四','王五','趙六','錢七'] Book.objects.all().delete() for title in titles: book = Book() book.title = title n = random.randint(0,len(authors)-1) book.author = authors[n] book.publisher = book.author book.time = datetime.datetime.today() book.version = '1' book.price = 1000 book.save() print('done')
def populate(): print('Populating Book...', end='') titles = [ '如何像電腦科學家一樣思考', '10 分鐘內學好 Python', '簡單學習 Django' '如何像電腦科學家一樣思考2', '10 分鐘內學好 Python2', '簡單學習 Django2' '如何像電腦科學家一樣思考3', '10 分鐘內學好 Python3', '簡單學習 Django3' '如何像電腦科學家一樣思考4', '10 分鐘內學好 Python4', '簡單學習 Django4' ] authors = ["張三", "李四", "王五", "趙六", "錢七"] Book.objects.all().delete() for title in titles: book = Book() book.title = title n = random.randint(0, len(authors) - 1) book.author = authors[n] book.publisher = book.author book.pubDate = datetime.datetime.today() book.price = 1000 book.save() print('done')
def populate(): # for authors for _ in range(100): Author.objects.create(first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email()) genres = [ 'Action', 'Crime', 'Drama', 'Fiction', 'Science fiction', 'Horror', 'Thriller', 'Fairytale', 'Adventure', 'Biography' ] for g in genres: Genre.objects.create(name=g) # for publisher for _ in range(100): Publisher.objects.create(name=fake.company(), address=fake.address(), website=fake.url()) # for books for _ in range(10000): book = Book(title=fake.sentence()) choices = range(1, 101) book.publisher_id = random.choice(range(1, 101)) book.genre_id = random.choice(range(1, 11)) book.price = random.randint(10, 500) book.published_date = fake.past_date(start_date="-100y") book.save() no_choice = [1, 2, 3, 4, 5] authors = random.choices(choices, k=random.choice(no_choice)) book.author.add(*authors) book.save() if _ % 100 == 0: print(f'{_} objects created')
def addbook(request): if request.method == 'POST': # user = cache.get('shuji') # print(user) user = request.user bookname = request.POST.get('bookname') author = request.POST.get('author') binding = request.POST.get('binding') publisher = request.POST.get('publisher') pubdate = request.POST.get('pubdate') price = request.POST.get('price') pages = request.POST.get('pages') isbn = request.POST.get('isbn') summary = request.POST.get('summary') image = request.FILES.get('image') book = Book() book.bookname = bookname book.author = author book.binding = binding book.publisher = publisher book.pubdate = pubdate book.price = price book.pages = pages book.isbn = isbn book.summary = summary book.image = image book.user_id_id = user.id book.save() user = User.objects.filter(pk=user.id).first() user.beans += 1 user.save() # recent = Book.objects.filter(user_id_id=user.id) recent = Book.objects.all() return render(request,'index.html',{'recent':recent,'user':user})
def create_book(request): """ @note: 添加图书信息 """ models = request.POST.get("models", "{}") models_json = json.loads(models) print models_json try: datalist = [] for data in models_json: if Book.objects.filter(title=data["title"]): return HttpResponse(json.dumps({"result": False, "message": u"书籍 %s 的信息已存在!" % data["title"]})) else: print "create" print data["publication_date"] print data["authors"] print data["publisher"] publisher = Publisher.objects.filter(name=data["publisher"])[0] print publisher book = Book() book.title = data["title"] book.publication_date = gt(data["publication_date"]) book.publisher = publisher book.price = data["price"] book.save() # 解析authors并添加 authors = data["authors"].split(",") authorlist = [] for name in authors: authorlist.append(Author.objects.filter(name=name)[0]) print authorlist for author in authorlist: book.authors.add(author) datalist.append(data) except Exception, e: print e return HttpResponse(json.dumps({"result": False, "message": u"添加记录失败, %s" % e}))
def create_book(request): ''' @note: 添加图书信息 ''' models = request.POST.get('models', '{}') models_json = json.loads(models) print models_json try: datalist = [] for data in models_json: if Book.objects.filter(title=data['title']): return HttpResponse(json.dumps({'result':False, 'message': u'书籍 %s 的信息已存在!' % data['title']})) else: print "create" print data['publication_date'] print data['authors'] print data['publisher'] publisher = Publisher.objects.filter(name=data['publisher'])[0] print publisher book = Book() book.title = data['title'] book.publication_date = gt(data['publication_date']) book.publisher = publisher book.price = data['price'] book.save() #解析authors并添加 authors = data['authors'].split(',') authorlist = [] for name in authors: authorlist.append(Author.objects.filter(name=name)[0]) print authorlist for author in authorlist: book.authors.add(author) datalist.append(data) except Exception, e: print e return HttpResponse(json.dumps({'result':False, 'message': u'添加记录失败, %s' % e}))
def postbox(request): if request.method == "POST": onedrive_data = json.loads(request.body) if onedrive_data['name'][-5] == '.': file_name, file_format = onedrive_data['name'][:-5], onedrive_data[ 'name'][-4:] elif onedrive_data['name'][-4] == '.': file_name, file_format = onedrive_data['name'][:-4], onedrive_data[ 'name'][-3:] else: h = HttpResponse('后缀名不合法') h.status = 404 return h if (file_format != 'epub') and (file_format != 'mobi') and ( file_format != 'azw3') and (file_format != 'pdf') and (file_format != 'kfx'): h = HttpResponse('后缀名不合法') h.status = 404 return h if Book.objects.filter(file_name=file_name): #如果存在这本书 b = Book.objects.get(file_name=file_name) b.save_url(onedrive_data['url'], file_format, onedrive_data['size']) b.save() else: #如果不存在这本书 douban_data = get_book_data(file_name) pprint(douban_data) b = Book() b.date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if douban_data: b.file_name = file_name b.title = douban_data['title'] if douban_data['subtitle']: b.subtitle = douban_data['subtitle'] if douban_data['alt_title']: b.english_title = douban_data['alt_title'] b.save() #为添加作者准备 author = douban_data.get('author') if author: #如果作者不为空 if len(author) == 1: a_inf = douban_data['author_intro'] else: a_inf = douban_data['author_intro'].split('\n')[1::2] al = [] if len(a_inf) == len(douban_data['author']): a_inf = a_inf else: a_inf = [ '不详' for i in range(len(douban_data['author'])) ] for i in range(len(douban_data['author'])): d = {} d['name'] = douban_data['author'][i] d['information'] = a_inf[i] al.append(d) for l in al: a = None if not Author.objects.filter(name=l['name']): #添加作者 a = Author() a.name = l['name'] a.information = l['information'] a.save() a.book.add(b) else: a = Author.objects.get(name=l['name']) a.book.add(b) b.author.add(a) if douban_data.get('price'): b.price = douban_data['price'] b.cover = 'https://images.weserv.nl/?url=' + douban_data[ 'images']['small'][8:] b.large_cover = 'https://images.weserv.nl/?url=' + douban_data[ 'images']['large'][8:] b.summary = douban_data['summary'] b.catalog = douban_data['catalog'] if not Publisher.objects.filter( name=douban_data['publisher']): #添加出版社 p = Publisher(name=douban_data['publisher']) p.save() else: p = Publisher.objects.get(name=douban_data['publisher']) b.publisher.add(p) p.book.add(b) b.save() b.douban_id = douban_data['id'] if douban_data['isbn10']: b.isbn10 = douban_data['isbn10'] if douban_data['isbn13']: b.isbn13 = douban_data['isbn13'] if douban_data['pages']: b.pages = douban_data['pages'] if douban_data.get('tags'): b.save() for d_t in douban_data['tags']: t = Tag() t.name = d_t['name'] t.title = d_t['title'] t.save() t.book.add(b) b.tags.add(t) s = douban_data.get('series') if s and type(s) == type({}): b.save() s = Series() s.name = douban_data.get('series')['title'] s.save() s.book.add(b) b.series.add(s) tr = douban_data.get('translator') pprint(tr) if tr and type(tr) == type([]): b.save() for tr in tr: if not Translator.objects.filter(name=tr): t = Translator() t.name = tr t.save() t.book.add(b) b.translator.add(t) else: b.translator.add(Translator.objects.get(name=tr)) b.save_url(onedrive_data['url'], file_format, onedrive_data['size']) else: b.file_name = b.title = file_name b.save_url(onedrive_data['url'], file_format, onedrive_data['size']) b.save() return render(request, 'book/404.html') else: return render(request, 'book/404.html', status=404)
def create_book4() -> None: book = Book() book.price = ('$', 10)
from book.models import Book from supplier.models import Supplier, SupplierStack from db_tools.data.book_data import raw_data # 先创建书库,将book_data中的所有书添加到这个书库中 book_stack = SupplierStack() book_stack.stack_name = "中国卖书有限公司书库" supplier = Supplier() supplier.supplier_name = "中国卖书有限公司" supplier.id = 1 book_stack.supplier = supplier supplier.save() book_stack.save() print("书库信息录入成功!") for book_detail in raw_data: book = Book() book.book_name = book_detail["book_name"] book.publisher = book_detail["publisher"] book.writer = book_detail["writer"] book.price = book_detail["price"] book.number = book_detail["number"] book.book_stack = book_stack book.save() print("图书信息录入成功!")
def create_book1() -> None: book = Book() book.price = Decimal('100.00') book.save()