def setUp(self): books = Book.objects.bulk_create([ Book( title="one", publication_date="1970-01-01", isbn="12345x", page_count=100, cover_photo="www.google.pl", publication_language="pl", ), Book( title="two", publication_date="1980-01-01", isbn="12346x", page_count=100, cover_photo="www.google.pl", publication_language="pl", ), Book( title="three", publication_date="1990-01-01", isbn="12347x", page_count=100, cover_photo="www.google.pl", publication_language="pl", ), ]) authors = Author.objects.bulk_create([ Author(name="Stephen King"), Author(name="Andriej Diakow"), Author(name="Dan Simmons"), ]) for author, book in zip(authors, books): book.authors.add(author)
def get_authors(self, authors_string): """ Get authors object from string names sepparated by commas Args: authors_string (String): names separated by commas Returns: List of Author: List of author objects """ names = self.separate(authors_string) authors = [] for name in names: try: author = Author.objects.get(name=name) authors.append(author) except Author.DoesNotExist: author = Author() author.name = name author.save() authors.append(author) return authors
def test_book_list_view_GET(self): response = self.client.get(self.book_list_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'books/book_list.html') self.assertEquals(Book.objects.count(), 0) author = Author( fullName='Author' ) author.save() isbn = IndustryIdentifier( isbn='ISBN_10', identifier='1234567890' ) isbn.save() book = Book( title='Title', publishedDate='2019', pageCount=0, language='en', smallThumbnail='http://books.google.com/books/content?id=hFfhrCWiLSMC&printsec=frontcover&img=1&zoom=5&source=gbs_api', thumbnail='http://books.google.com/books/content?id=hFfhrCWiLSMC&printsec=frontcover&img=1&zoom=1&source=gbs_api' ) book.save() book.authors.add(author) book.industryIdentifiers.add(isbn) self.assertEquals(Book.objects.count(), 1)
def handle(self, *args, **kwargs): Book.objects.all().delete() Author.objects.all().delete() for name, books in [ ('Alice', [ ('The Great Read', datetime(2020, 11, 1)), ('Super Duper Book', datetime(2020, 12, 15)), ]), ('Bob', [ ('Mystery Novel', datetime(2020, 10, 1)), ('Hidden Secrets', datetime(2020, 11, 10)), ('The Great Reveal', datetime(2020, 11, 20)), ]), ('Charlie', [ ('Secrets of the Place', datetime(2021, 2, 15)), ('Survival Guide', datetime(2020, 12, 15)), ]), ]: author = Author(name=name) author.save() for book in books: Book( title=book[0], published=book[1], author=author, ).save()
def setUp(self): folder = "%s/test_files/" % os.path.dirname(os.path.realpath(__file__)) # Load authors authors = json.loads(open(folder + 'authors.json', 'r').read()) Author.objects.bulk_create( [Author(name=item["name"]) for item in authors])
def handle(self, *args, **options): time_start = datetime.now() # Get parameters path = options.get("csv_file", "") colname = options.get("column_name", "name") # Check if file exists if not path or not os.path.exists(path): raise CommandError("File not found: %s" % path) # Read file try: content = read_csv(path, usecols=[colname], skip_blank_lines=True, chunksize=1000000) except Exception as e: raise CommandError("Error reading the file: %s" % str(e)) # Import authors imported = 0 for chunk in content: values = chunk.to_dict()[colname].values() Author.objects.bulk_create([Author(name=name) for name in values]) imported += chunk.size print(imported, 'imported') time_end = datetime.now() - time_start print("Finished! %d authors successfully imported. Time: %s" % (imported, str(time_end)))
def insert_Author(request,lastname): author = Author(last_name = lastname,first_name = 'liu',email = '*****@*****.**') author.save() ret = { "result": True, } return HttpResponse(simplejson.dumps(ret), mimetype="application/json")
def test_models(self): data_dicts = set_up_data() self.assertTrue(Collection(data_dicts['c'])) self.assertTrue(Publisher(data_dicts['p'])) self.assertTrue(Author(data_dicts['a'])) self.assertTrue(Book(data_dicts['b1'])) self.assertTrue(Book(data_dicts['b2']))
def get_authors_list(self, author_names): """ Process the list of authors names, returns a list of corresponding objects, creates new objects if don't exist Args: author_names (List of String): Author names Returns: List of Athor: Author objects """ authors = [] for author_name in author_names: try: author = Author.objects.get(name=author_name) authors.append(author) except Author.DoesNotExist: author = Author() author.name = author_name author.save() authors.append(author) return authors
def _save_author(self): print('... Save Model Author ...') authors = self.df_books['author'] for a in authors: author = Author(name=a) try: author.save() except IntegrityError: pass
def handle(self, *args, **options): faker = Faker("pl_PL") for i in range(10): author = Author() author.first_name = faker.first_name() author.last_name = faker.last_name() author.birthday = faker.date_of_birth() author.save() self.stdout.write(self.style.SUCCESS(f'Create: {str(author)}'))
def handle(self, *args, **kwargs): fake = Faker() total = kwargs['total'] authors_list = [] for _ in range(total): name = fake.name() first_name = name.split()[0] last_name = name.split()[1] date_of_birth = fake.date() date_of_death = fake.date() country = fake.country() gender = random.choice(['male', 'female']) native_language = random.choice( ['English', 'French', 'Russian', 'Ukrainian']) authors_list.append( Author( first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, date_of_death=date_of_death, country=country, gender=gender, native_language=native_language, )) Author.objects.bulk_create(authors_list) category_list = [] for _ in range(total): name = random.choice([ 'Action', 'Detectives', 'Romance novels', 'Adventures', 'Fantasy', 'Humorous literature', 'Contemporary prose', 'History', 'Classic literature', "Children's books", 'Psychology', 'Business books', 'Journalism', 'Sports, health, beauty', 'For parents' ]) category_list.append(Category(name=name, )) Category.objects.bulk_create(category_list) books_list = [] for _ in range(total): author = Author.objects.order_by('?').last() title = fake.word() category = Category.objects.order_by('?').last() publish_year = random.randint(0, datetime.now().year) review = fake.text() condition = random.randint(1, 5) books_list.append( Book( author=author, title=title, category=category, publish_year=publish_year, review=review, condition=condition, )) Book.objects.bulk_create(books_list)
def authors_db(cls, books): """ put authors' name into the table """ for book in books: authors = book["volumeInfo"].get("authors") if authors is not None: for author in authors: try: Author.objects.bulk_create( [Author(author_name=author)]) except (IntegrityError, DataError): continue
def getPostData(request): print request.POST print request.FILES if "name" in request.POST: lastname = request.POST['name'] else: lastname = "" author = Author(last_name = lastname,first_name = 'liu',email = '*****@*****.**') author.save() ret = { "result": True, } return HttpResponse(simplejson.dumps(ret), mimetype="application/json")
def handle(self, *args, **options): fake = Faker() # generate Categories for _ in range(20): Category.objects.create(name=fake.word()) # create authors authors = [] for _ in range(1_000): first_name = fake.name() last_name = fake.word() authors.append(Author( first_name=first_name, last_name=last_name, ))
def handle(self, *args, **options): Book.objects.all().delete() Publisher.objects.all().delete() Author.objects.all().delete() print('* Populating books...') orderedLS = OrderedDict(lifestudies) p = Publisher(name='Living Stream Ministry', code='LSM') p.save() a = Author(first_name='Witness', last_name='Lee') a.save() for b, c in orderedLS.items(): print b b = Book(publisher=p, name=b, chapters=c) b.save() b.author = (a,) b.save()
def setUp(self): folder = "%s/test_files/" % os.path.dirname(os.path.realpath(__file__)) # Load authors authors = json.loads(open(folder + 'authors.json', 'r').read()) Author.objects.bulk_create( [Author(name=item["name"]) for item in authors]) # Load books books = json.loads(open(folder + 'books.json', 'r').read()) for b in books: book = Book.objects.create( name=b["name"], edition=b["edition"], publication_year=b["publication_year"], ) book.authors.add(*b["authors"])
def import_authors(all_data, options): """"Import authors from JSON data.""" for k, val in all_data["authors"].items(): # If already there, overwrite: try: author = Author.objects.get(pk=k) except ObjectDoesNotExist: author = Author(pk=k) author.name = val["name"] msg = f"Imported [AUTHOR] {author}" print(msg) if not options.dry_run: author.save()
def handle(self, *args, **kwargs): file_path = kwargs['file_path'] with open(file_path) as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader, None) for row in csv_reader: name = str(row).strip("'[]") try: author = Author(name=name) author.save() self.stdout.write( self.style.SUCCESS( f"Author {name} added successfully")) except: self.stdout.write(self.style.ERROR("Something went wrong"))
def new_author_book(request): json_data = simplejson.loads(request.body) book_title = json_data['title'] name = json_data['name'] if not Book.objects.filter(title=book_title, author_name=name).exists(): b = Book(title=book_title, author_name=name) b.save() else: return HttpResponse("Success") author_name = name if Author.objects.filter(name=author_name).exists(): a = Author.objects.get(name=author_name) a.books.add(b) a.save() else: a = Author(name=author_name) a.save() a.books.add(b) a.save() return HttpResponse("Success")
def set_up_data(): # model1: Collection c = Collection(name="Life Studies", code="LS") # model2: Publisher p = Publisher(name="Living Stream Ministry", code="LSM") # model3: Author a = Author(first_name="Witness", last_name="Lee", code="WL") # make sure all fields allowing blanks are tested # model4: Book without author and chapters ascribed b1 = Book(isbn=1234567890, name="Life Study of Genesis volume 1", code="LSG1", collection=c, publisher=p) # model5: Book without collection ascribed b2 = Book(isbn=1234567891, name="Life Study of Genesis volume 2", code="LSG2", chapters=25, publisher=p) return dict([('c', c), ('p', p), ('a', a), ('b1', b1), ('b2', b2)])
def handle(self, *args, **kwargs): fake = Faker() amount = kwargs['amount'] authors = [] for _ in range(amount): first_name = fake.word().capitalize() last_name = fake.word().capitalize() date_of_birth = fake.date() date_of_death = fake.date() country = fake.country() gender = random.choice(['Male', 'Female']) language = fake.word() authors.append( Author(first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, date_of_death=date_of_death, country=country, gender=gender, language=language)) Author.objects.bulk_create(authors) books_list = [] for _ in range(amount): author = Author.objects.order_by('?').last() title = fake.word() category = random.choice(Category.objects.all()) publish_year = random.randint(0, datetime.now().year) review = fake.text() condition = random.randint(1, 5) books_list.append( Book( author=author, title=title, category=category, publish_year=publish_year, review=review, condition=condition, )) Book.objects.bulk_create(books_list)
def handle(self, *args, **options): fake = Faker() authors_list = [] for _ in range(options['quant']): first_name = fake.first_name() last_name = fake.last_name() country = fake.country() date_of_birth = fake.date() date_of_death = fake.date() gender = bool(random.getrandbits(1)) native_language = fake.country_code() authors_list.append( Author(first_name=first_name, last_name=last_name, country=country, date_of_birth=date_of_birth, date_of_death=date_of_death, gender=gender, native_language=native_language)) Author.objects.bulk_create(authors_list)
def form_valid(self, form): title = form.cleaned_data['title'] isbn = form.cleaned_data['isbn'] authors = form.cleaned_data['authors'] create_new_author = form.cleaned_data['create_new_author'] categories = form.cleaned_data['categories'] author_name = form.cleaned_data['author_name'] author_surname = form.cleaned_data['author_surname'] book = Book(title=title, isbn=isbn, average_rating=0) book.save() if create_new_author is True: new_author = Author(name=author_name, surname=author_surname) new_author.save() book.book_author.add(new_author) else: author_list = Author.objects.filter(pk__in=authors) for author in author_list: book.book_author.add(author) category_list = Category.objects.filter(pk__in=categories) for category in category_list: book.book_category.add(category) return redirect('books/{}'.format(book.id))
__str__()唯一的条件是返回一个string, 如果不返回 string 的话如返回一个 integer ,会触发一个TypeError异常 __str__()方法告诉Python怎样显示对象的string显示: # 修改前面的 Author 类 class Author(models.Model): name = models.CharField(max_length=30) salutation = models.CharField(max_length=10) def __str__(self): return self.name def __unicode__(self): return unicode(self.name) # 执行命令 python manage.py shell # 执行python from books.models import Author # import模型类 a = Author(name='Jhon', salutation='salutation1') a.save() a = Author(name='Kevin', salutation='salutation2') a.save() author_list = Author.objects.all() print(author_list) # 打印: [<Author: Jhon>, <Author: Kevin>] print(author_list[0].name) # 打印: Jhon 注意 __str__() 是给模型添加行为的好习惯 一个Django模型描述的不仅仅是一个对象数据库表结构, 它也描述了对象知道怎样去做的功能
def setUp(self): self.book = Book(**example_book_attrs) self.author = Author(**example_author_attrs) self.isbn = ISBN(**example_isbn_attrs)
def test_create_author_with_exists_name_raises_error(self): author = AuthorFactory() new_author = Author(first_name=author.first_name, last_name=author.last_name) with self.assertRaises(IntegrityError): new_author.save()
def run(inp_list=None, tbr_name=None): cont = [] log = [] new_author = 0 new_book = 0 new_genres = 0 new_tbr = 0 records_json = json.loads(inp_list) if tbr_name: tbr_slug = unique_slug_generator(tbr_name) try: tbr = TBR.objects.get(slug=tbr_slug) return None except TBR.DoesNotExist: log.append("Creating a new TBR: {}".format(tbr_name)) tbr = TBR(title=tbr_name) tbr.save() new_tbr = +1 tbr = TBR.objects.get(slug=tbr_slug) for record in records_json: auth_name_refined = remove(record['author_name']) auth_name = auth_name_refined.split(",") # Loading Authors to the database, if doesn't exist. Creating one for ind_auth_name in auth_name: firstname = ind_auth_name.strip().split(' ')[0] lastname = ' '.join( (ind_auth_name + ' ').split(' ')[1:]).strip() auth_slug = unique_slug_generator_author(ind_auth_name) try: author = Author.objects.get(slug=auth_slug) log.append("Auhtor: {},{} exists.".format( lastname, firstname)) except Author.DoesNotExist: log.append("Author: {} {} does not exist.".format( lastname, firstname)) author = Author(first_name=firstname, last_name=lastname) author.save() new_author = +1 log.append("Author: {} {} Added.".format( lastname, firstname)) #Loading Books to the database. if doesn't exist. Creating one try: book = Book.objects.get(slug=record["book_slug"]) for auth in auth_name: auth_slug = unique_slug_generator_author(auth) log.append("Book: {} Exists.".format( record["book_title"])) author = Author.objects.get(slug=auth_slug) book.author.add(author) book.save() log.append("Added Author to Book: {}.".format( record["book_title"])) tbr.book.add(book) tbr.save() log.append( "Added Book to Reading List: {}.".format(tbr_name)) except Book.DoesNotExist: log.append("Book: {} does not exist.".format( record["book_title"])) book = Book(title=record["book_title"], image_url=record["image_url"]) book.save() new_book += 1 log.append("Book: {} Added.".format(record["book_title"])) book = Book.objects.get(slug=record["book_slug"]) for auth in auth_name: auth_slug = unique_slug_generator_author(auth) author = Author.objects.get(slug=auth_slug) book.author.add(author) book.save() log.append("Added Author to Book: {}.".format( record["book_title"])) tbr.book.add(book) tbr.save() log.append( "Added Book to Reading List: {}.".format(tbr_name)) # Loading Genre to the database. if doesn't exist. Creating One if record['genre']: genre_refined = remove(record['genre']) genre_name = genre_refined.split(",") for genre in genre_name: genre_slug = unique_slug_generator(genre) try: gen = Genre.objects.get(slug=genre_slug) log.append("Genre: {} Exists.".format(genre)) except Genre.DoesNotExist: log.append( "Genre: {} does not exist.".format(genre)) gen = Genre(name=genre) gen.save() new_genres += 1 log.append("Genre: {} added.".format(genre)) # Adding Genres to the books try: book = Book.objects.get(slug=record["book_slug"]) for genre in genre_name: genre_slug = unique_slug_generator_author(genre) log.append("Book: {} Exists.".format( record["book_title"])) genre = Genre.objects.get(slug=genre_slug) book.genre.add(genre) book.save() log.append("Added Genre{} to Book: {}.".format( genre, record["book_title"])) except Exception as e: pass else: for record in records_json: auth_name_refined = remove(record['author_name']) auth_name = auth_name_refined.split(",") # Loading Authors to the database, if doesn't exist. Creating one for ind_auth_name in auth_name: firstname = ind_auth_name.strip().split(' ')[0] lastname = ' '.join( (ind_auth_name + ' ').split(' ')[1:]).strip() auth_slug = unique_slug_generator_author(ind_auth_name) try: author = Author.objects.get(slug=auth_slug) log.append("Auhtor: {},{} exists.".format( lastname, firstname)) except Author.DoesNotExist: log.append("Author: {} {} does not exist.".format( lastname, firstname)) author = Author(first_name=firstname, last_name=lastname) author.save() new_author += 1 log.append("Author: {} {} Added.".format( lastname, firstname)) #Loading Books to the database. if doesn't exist. Creating one try: book = Book.objects.get(slug=record["book_slug"]) for auth in auth_name: auth_slug = unique_slug_generator_author(auth) log.append("Book: {} Exists.".format(record["book_title"])) author = Author.objects.get(slug=auth_slug) book.author.add(author) book.save() log.append("Added Author to Book: {}.".format( record["book_title"])) except Book.DoesNotExist: log.append("Book: {} does not exist.".format( record["book_title"])) # book = Book(title=record["book_title"]) book = Book(title=record["book_title"], image_url=record["image_url"]) book.save() new_book += 1 log.append("Book: {} Added.".format(record["book_title"])) book = Book.objects.get(slug=record["book_slug"]) for auth in auth_name: auth_slug = unique_slug_generator_author(auth) author = Author.objects.get(slug=auth_slug) book.author.add(author) book.save() log.append("Added Author to Book: {}.".format( record["book_title"])) # Loading Genre to the database. if doesn't exist. Creating One if record['genre']: genre_refined = remove(record['genre']) genre_name = genre_refined.split(",") for genre in genre_name: genre_slug = unique_slug_generator(genre) try: gen = Genre.objects.get(slug=genre_slug) log.append("Genre: {} Exists.".format(genre)) except Genre.DoesNotExist: log.append("Genre: {} does not exist.".format(genre)) gen = Genre(name=genre) gen.save() new_genres = +1 log.append("Genre: {} added.".format(genre)) # Adding Genres to the books try: book = Book.objects.get(slug=record["book_slug"]) for genre in genre_name: genre_slug = unique_slug_generator_author(genre) log.append("Book: {} Exists.".format(record["book_title"])) genre = Genre.objects.get(slug=genre_slug) book.genre.add(genre) book.save() log.append("Added Genre{} to Book: {}.".format( genre, record["book_title"])) except Exception as e: pass cont.append(new_author) cont.append(new_book) cont.append(new_genres) cont.append(new_tbr) cont.append(log) return cont
def test_string_representation(self): author = Author(name='John Smith') self.assertEqual(str(author.name), 'John Smith')
def authors(db): authors = [ Author(first_name='Massimo', last_name='Costa'), Author(first_name='Roberto', last_name='Costa'), ] return Author.objects.bulk_create(authors)