Section 5 Performing CRUD operations

クラスの見方

float, string, Date Timeなど色々な定義お方法がある。

class Book(db.Model):
    __tablename__ = 'book'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500), nullable=False, index=True)
    avg_rating = db.Column(db.Float)
    pub_date = db.Column(db.DateTime, default=datetime.utcnow())

今回やる事は3つ

  1. Create table
  2. Establishing Relationships
  3. Insert Data into DB

新しいテーブルの追加方法

class Book(db.Model):
    __tablename__ = 'book'   #テーブルの名前
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500), nullable=False, index=True)
    author = db.Column(db.String(350))

    def __init__(self, title, author, avg_rating, book_format, image, num_pages, pub_id):
        self.title = title
        self.author = author

    def __repr__(self):
        return '{} by {}'.format(self.title, self.author)

intとreprがよくわからん

3段構えの流れ ①class Book(db.Model): tablename = 'book' ②def init ③def repr(self):

ターミナルでデータの追加

データベースをimportして3つのことをするだけ。
from run import db, Book ①create instances ②add the session ③commit db 

>>>> from run import db, Book
>>> b1 = Book("test title", 'test author', 3.9, 'epub', 'broom-12345.svg',123, 100)
>>> b2 = Book("test title2", 'test2 author', 2.3, 'epub', 'broom-125.svg',124, 100)
>>> db.session.add_all([b1,b2])
>>> db.session.commit()

f:id:yukking3:20180503101453p:plain

Primary Keyのリンクとデータベース f:id:yukking3:20180503101715p:plain