44"""
55
66from importlib import resources
7+
78from sqlalchemy import and_ , create_engine
89from sqlalchemy .orm import sessionmaker
910from sqlalchemy .sql import asc , desc , func
10- from treelib import Tree
1111
12- from project .modules .models import Author , Book , Publisher
12+ from project .modules .models import Author , Book , Publisher , author_publisher
13+ from treelib import Tree
1314
1415
1516def get_books_by_publishers (session , ascending = True ):
@@ -87,14 +88,25 @@ def add_new_book(session, author_name, book_title, publisher_name):
8788 .filter (Book .publishers .any (Publisher .name == publisher_name ))
8889 .one_or_none ()
8990 )
90-
9191 # Does the book by the author and publisher already exist?
9292 if book is not None :
9393 return
94- # Otherwise, create the book
95- else :
94+
95+ # get the book by the author
96+ book = (
97+ session .query (Book )
98+ .join (Author )
99+ .filter (Book .title == book_title )
100+ .filter (
101+ and_ (
102+ Author .first_name == first_name , Author .last_name == last_name
103+ )
104+ )
105+ .one_or_none ()
106+ )
107+ # Create the new book if needed
108+ if book is None :
96109 book = Book (title = book_title )
97- session .add (book )
98110
99111 # Get the author
100112 author = (
@@ -106,11 +118,15 @@ def add_new_book(session, author_name, book_title, publisher_name):
106118 )
107119 .one_or_none ()
108120 )
109- # Do we need to create the author
121+ # Do we need to create the author?
110122 if author is None :
111123 author = Author (first_name = first_name , last_name = last_name )
112124 session .add (author )
113125
126+ # Is this a new book for this author?
127+ if book not in [book_ for book_ in author .books ]:
128+ author .books .append (book )
129+
114130 # Get the publisher
115131 publisher = (
116132 session .query (Publisher )
@@ -122,14 +138,10 @@ def add_new_book(session, author_name, book_title, publisher_name):
122138 publisher = Publisher (name = publisher_name )
123139 session .add (publisher )
124140
125- # Add the book to the author's books collection
126- author .books .append (book )
127-
128- # Add the book to the publisher's books collection
129- publisher .books .append (book )
130-
131- # Add the publisher to the author's publishers collection
132- author .publishers .append (publisher )
141+ # Initialize the book relationships
142+ book .author = author
143+ book .publishers .append (publisher )
144+ session .add (book )
133145
134146 # Commit to the database
135147 session .commit ()
0 commit comments