コード例 #1
0
from sqlalchemy import Column, Integer, ForeignKey, String, Table, Text
from sqlalchemy.orm import relationship

from basic_.sqlalchemy_.schemas import User, Database

session = Database.get_session(echo=True)

# association table
# We can see declaring a Table directly is a little different than declaring a mapped class. Table is a constructor function,
# so each individual Column argument is separated by a comma.
# The Column object is also given its name explicitly, rather than it being taken from an assigned attribute name.
post_keywords = Table(
    'post_keywords', Database.Base.metadata,
    Column('post_id', ForeignKey('posts.id'), primary_key=True),
    Column('keyword_id', ForeignKey('keywords.id'), primary_key=True))


class BlogPost(Database.Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    headline = Column(String(255), nullable=False)
    body = Column(Text)

    # many to many BlogPost<->Keyword
    keywords = relationship('Keyword',
                            secondary=post_keywords,
                            back_populates=__tablename__)

    # note: declarations illustrate explicit __init__() methods. Remember, when using Declarative, it’s optional!
    def __init__(self, headline, body, author):
コード例 #2
0
from basic_.sqlalchemy_.schemas import Database, horizontal_rule, User, Address

session = Database.get_session(echo=True)

jack = User(name='jack', fullname='Jack Bean', nickname='gjffdd')
print(jack.addresses)

horizontal_rule()

jack.addresses = [
    Address(email_address='jack@google'),
    Address(email_address='*****@*****.**'),
]

horizontal_rule()

print(jack.addresses[0])
print(jack.addresses[1].user)

horizontal_rule()

session.add(jack)
session.commit()

jack = session.query(User).filter_by(name='jack').one()
print(jack)
print(jack.addresses)
print(jack.addresses[0].user)

bob: User = session.query(User).filter(
    User.fullname == 'Bob Allan Smith').one_or_none()
コード例 #3
0
class MyClass(Database.Base):
    __table__ = Table("some_table",
                      Database.Base.metadata,
                      autoload=True,
                      autoload_with=Database.get_engine())