예제 #1
0
    def handle(self, *args, **options):
        book = Book.objects.get(title='Good Omens')
        print(book.title)
        print(book.year_published)

        print(book.authors.all())
        for author in book.authors.all():
            print(author.name)

        author = Author.objects.get(name='Terry Pratchett')
        print(author.books.all())
        for book in author.books.all():
            print(book.title)

        # book = Book(title='Tiny Pretty Things', year_published=2019)
        # book.save()

        # author1 = Author(name='Sona Charaipotra')
        # author1.save()

        # author2 = Author(name='Dhonielle Clayton')
        # author2.save()

        # book.authors.add(author1)
        # book.authors.add(author2)

        # book.authors.set([author1, author2])

        # book.authors.clear()

        books_data = [{
            'title': 'Hogfather',
            'year_published': 1996,
            'authors': ['Terry Pratchett']
        }, {
            'title': 'Wyrd Sisters',
            'year_published': 1988,
            'authors': ['Terry Pratchett']
        }]

        for book_data in books_data:
            title = book_data['title']
            year_published = book_data['year_published']

            book = Book(title=title, year_published=year_published)
            book.save()

            for author_name in book_data['authors']:

                # author = author.objects.get(name=author_name)

                # author = Author(name=author_name)
                # author.save()

                author, created = Author.objects.get_or_create(
                    name=author_name)

                book.authors.add(author)
예제 #2
0
파일: views.py 프로젝트: danimilles/Mobooks
def populate_database(request):
    mobooks_db = connect_to_db()

    books_collection = mobooks_db['main_book']
    books_collection.drop()
    with open('static/pop_data/books.json') as file:
        data = json.load(file)
        for datum in data:
            book = Book(title=datum['title'],
                        release_year=datum['release_year'],
                        author=datum['author'],
                        genre=datum['genre'],
                        publisher=datum['publisher'],
                        synopsis=datum['synopsis'],
                        available_quantity=datum['available_quantity'])
            Book.save(book)

    authors_collection = mobooks_db['main_author']
    authors_collection.drop()
    with open('static/pop_data/authors.json') as file:
        data = json.load(file)
        for datum in data:
            author = Author(name=datum['author'])
            Author.save(author)

    genres_collection = mobooks_db['main_genre']
    genres_collection.drop()
    with open('static/pop_data/genres.json') as file:
        data = json.load(file)
        for datum in data:
            genre = Genre(name=datum['genre'])
            Genre.save(genre)

    publishers_collection = mobooks_db['main_publisher']
    publishers_collection.drop()
    with open('static/pop_data/publishers.json') as file:
        data = json.load(file)
        for datum in data:
            publisher = Publisher(name=datum['publisher'])
            Publisher.save(publisher)
    return redirect('/')
예제 #3
0
def add_book(category, el):
    kwargs = get_book_dict(el)
    b = Book(**kwargs)
    cover_fname = get_book_cover(el)
    if cover_fname is not None:
        b.book_cover.name = cover_fname
    try:
        b.save()
    except:
        print("Error saving book %s" % b.title, sys.exc_info())
    else:
        b.categories.add(category)
        folders = get_or_create_folders(el)
        if folders is not None:
            for f in folders:
                b.folders.add(f)
            try:
                b.save()
            except:
                print("Error saving folders of book %s" % b.title,
                      sys.exc_info())
예제 #4
0
    def put(self, request, id=None):
        post = request.POST
        if not self._validate(post.keys()):
            return JsonResponse(self.parameter_error_resp)

        authors = self._get_authors_or_fail(post['authors'])
        if not authors:
            return JsonResponse(self.authors_error_resp)

        del post['authors']
        book = Book(id=id)
        for key, value in post.items():
            setattr(book, key, value)
        book.save()
        book.authors.clear()
        book.authors.add(*authors)

        resp = {
            'status': 200,
            'result': Book.objects.get_from_id_with_authors(id)
        }
        return JsonResponse(resp)
예제 #5
0
def second_loader():
    df = pd.read_csv('main/management/commands/final_df.csv')
    for book_title in df['title'].unique():
        print(f'Adding {book_title} to the DB')
        filtered = df[df['title'] == book_title].head(1)
        for index, row in filtered.iterrows():
            title_en = row['title_en']
            title_pt = row['title_pt']
            author = row['author_y']
            isbn_pt = row['isbn_pt']
            isbn_en = row['id_code']
            img_url = row['img_amz']
            newbook = Book(title_en=title_en,
                           title_pt=title_pt,
                           author=author,
                           isbn_pt=isbn_pt,
                           isbn_en=isbn_en,
                           img_url=img_url)
            newbook.save()
    for celeb in df['influencer'].unique():
        print(f'Adding {celeb} to the DB')
        influencer = Influencer(name=celeb)
        influencer.save()
        filtered_df = df[df['influencer'] == celeb]
        for index, row in filtered_df.iterrows():
            try:
                print(
                    f'Added book {row["title"]} to the recommended by {celeb}')
                book_to_add = Book.objects.get(isbn_en=row['id_code'])
                influencer.recommended_books.add(book_to_add)
            except Exception as e:
                print(
                    f'An exception occured when trying to add books for {celeb},\
                    trying to add row: {row} \n got the following exception: {str(e)}'
                )


### testing a change
예제 #6
0
def create(request):
    # Get the user object for the logged in user
    this_user = User.objects.get(id=request.session['userid'])

    # Add new book and review
    print(request.POST)

    if request.POST['author_name'] != '':
        # Check if that author name is already in the database
        # ...And if it is, then use the existing record, do not add a new author
        authors_found = Author.objects.filter(
            name=request.POST['author_name'].strip())
        if authors_found:
            this_author = authors_found[0]
        else:
            # Adding a new author
            this_author = Author(name=request.POST['author_name'].strip())
            this_author.save()
            print('new_author.name', this_author.name)

    else:
        print('Using an author from select list')
        # get the user pulled from the select menu
        this_author = Author.objects.get(id=request.POST['author_list'])
        print('this_author', this_author.name, this_author.id)

    # Add the book
    new_book = Book(title=request.POST['title'],
                    author=this_author, user=this_user)
    new_book.save()

    # Add the review
    new_review = Review(
        text=request.POST['review'], rating=request.POST['rating'], book=new_book, user=this_user)
    new_review.save()

    return redirect('/books/'+str(new_book.id))
예제 #7
0
def create_books(num_entries=15, overwrite=False):

    if overwrite:
        Book.objects.all().delete()
    choices = [
        'Snake Of The Land', 'Army Of The North', 'Wives Without Glory',
        'Priests Of The Prison', 'Girls And Defenders', 'Slaves And Enemies',
        'Wand Of Eternity', 'Spear Without Courage', 'Meeting At The Future',
        'Guarded By My Home', 'God Of The Ancestors', 'Owl Of Next Year',
        'Gods With Money', 'Butchers With Silver', 'Serpents And Witches',
        'Serpents And Mice', 'Murder Of Freedom', 'Love Of The World',
        'Blood At The Dark', 'Eating At Myself'
    ]
    users = list(UserProfile.objects.all())
    for _ in range(num_entries):
        b = Book(name=random.choice(choices),
                 author=fake.name(),
                 user=random.choice(users),
                 price=fake.random_int(1, 9999),
                 pages_count=fake.random_int(1, 10),
                 created_add=fake.date_time_this_month(),
                 updated_add=fake.date_time_this_month(),
                 amazon_rating=fake.random_int(1, 10))
        b.save()
예제 #8
0
 def post(request):
     book = Book(**request.info)
     book.id = None
     book.save()
     return RestJsonResponse(book)