| 1 | from flask_sqlalchemy import SQLAlchemy |
| 2 | |
| 3 | db = SQLAlchemy() |
| 4 | |
| 5 | class Author(db.Model): |
| 6 | __tablename__ = 'authors' |
| 7 | id = db.Column(db.Integer, primary_key=True, autoincrement=True) |
| 8 | name = db.Column(db.String(100)) |
| 9 | birth_date = db.Column(db.Date) |
| 10 | date_of_death = db.Column(db.Date) |
| 11 | |
| 12 | books = db.relationship( |
| 13 | 'Book', |
| 14 | back_populates='author', |
| 15 | cascade='all, delete-orphan', |
| 16 | passive_deletes=True |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | def __str__(self): |
| 21 | output = f'Name: {self.name}, Birth Date: {self.birth_date}' |
| 22 | return output |
| 23 | |
| 24 | |
| 25 | class Book(db.Model): |
| 26 | __tablename__ = 'books' |
| 27 | id = db.Column(db.Integer, primary_key=True, autoincrement=True) |
| 28 | isbn = db.Column(db.String(13), unique=True) |
| 29 | title = db.Column(db.String(100)) |
| 30 | publication_year = db.Column(db.Integer) |
| 31 | author_id = db.Column(db.Integer, db.ForeignKey('authors.id', ondelete='CASCADE'), nullable=False) |
| 32 | rating = db.Column(db.Float, default=0.0) |
| 33 | |
| 34 | author = db.relationship('Author', back_populates='books') |
| 35 | |
| 36 | def __str__(self): |
| 37 | output = f'Title: {self.title}, Year: {self.year}' |
| 38 | return output |