added in publisher relationship (via book_publisher_link), removed debug, also removed ma.Nested, not needed?

This commit is contained in:
2020-11-04 23:48:09 +11:00
parent 2a7cbe5845
commit 21c792203c
2 changed files with 22 additions and 7 deletions

27
main.py
View File

@@ -17,6 +17,11 @@ book_author_link = db.Table('book_author_link', db.Model.metadata,
db.Column('author_id', db.Integer, db.ForeignKey('author.id'))
)
book_publisher_link = db.Table('book_publisher_link', db.Model.metadata,
db.Column('book_id', db.Integer, db.ForeignKey('book.id')),
db.Column('publisher_id', db.Integer, db.ForeignKey('publisher.id'))
)
class Book(db.Model):
id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
title = db.Column(db.String(100), unique=True, nullable=False)
@@ -31,9 +36,10 @@ class Book(db.Model):
modified = db.Column(db.Date)
author = db.relationship('Author', secondary=book_author_link)
publisher = db.relationship('Publisher', secondary=book_publisher_link)
def __repr__(self):
return "<title: {}, id: {} author: {}>".format(self.title, self.id, self.author )
return "<title: {}, id: {}>".format(self.title, self.id )
class Author(db.Model):
id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
@@ -43,9 +49,14 @@ class Author(db.Model):
book = db.relationship('Book', secondary=book_author_link )
def __repr__(self):
return "<firstnames: {}, surname: {}, book: {}>".format(self.firstnames, self.surname, self.book)
return "<firstnames: {}, surname: {}, id: {}>".format(self.firstnames, self.surname, self.id)
class Publisher(db.Model):
id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
name = db.Column(db.String(50), unique=False, nullable=False)
def __repr__(self):
return "<name: {}, id: {}>".format(self.name, self.id)
### setup serializer schemas, to make returning books/authors easier
class AuthorSchema(ma.SQLAlchemyAutoSchema):
@@ -54,17 +65,21 @@ class AuthorSchema(ma.SQLAlchemyAutoSchema):
include_relationships = True
load_instance = True
class PublisherSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Publisher
include_relationships = True
load_instance = True
class BookSchema(ma.SQLAlchemyAutoSchema):
author = ma.Nested(AuthorSchema, many=True)
class Meta:
model = Book
include_relationships = True
load_instance = True
book_schema = BookSchema()
author_schema = AuthorSchema()
print( book_schema )
publisher_schema = PublisherSchema()
book_schema = BookSchema()
####################################### ROUTES #######################################
@app.route("/books", methods=["GET"])

View File

@@ -23,7 +23,7 @@
<tr>
<td data-sort="{{book.id}}"><a href="/book/{{book.id}}">{{book.title}}</a></td>
<td>{{ book.author[0]['surname'] }}, {{book.author[0]['firstnames']}}</td>
<td>{{ book.publisher}}</td>
<td>{{ book.publisher[0]['name']}}</td>
<td align="center">
{% if book.condition == "Good" %}
<i class="fas fa-book" style="color:black"></i>