Created
June 23, 2014 05:57
-
-
Save Zuckonit/bda13c6408427f57b7ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.orm import relationship | |
from sqlalchemy import Column, ForeignKey | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.dialects.mysql import INTEGER, CHAR | |
Base = declarative_base() | |
class User(Base): | |
__tablename__ = 'user' | |
__table_args__ = {'mysql_engine': 'InnoDB', 'sqlite_autoincrement': True, 'mysql_charset': 'utf8'} | |
id = Column(INTEGER(unsigned=True), nullable=False, autoincrement=True, primary_key=True) | |
name = Column(CHAR(32), nullable=False) | |
class Address(Base): | |
__tablename__ = 'address' | |
__table_args__ = {'mysql_engine': 'InnoDB', 'sqlite_autoincrement': True, 'mysql_charset': 'utf8'} | |
id = Column(INTEGER(unsigned=True), nullable=False, autoincrement=True, primary_key=True) | |
place = Column(CHAR(32), nullable=False) | |
user_id = Column(INTEGER(unsigned=True), ForeignKey("user.id"), nullable=False, unique=True) | |
user = relationship("User", foreign_keys=[user_id], backref="addresses") | |
from sqlalchemy import create_engine | |
dsn = "mysql+mysqlconnector://test:test@localhost/test?charset=utf8&use_unicode=0" | |
engine = create_engine(dsn) | |
Base.metadata.create_all(engine) | |
from sqlalchemy.orm import sessionmaker | |
s = sessionmaker(bind=engine)() | |
jack = User(name='jack') | |
jack.addresses = [ | |
Address(place='where'), | |
Address(place='here') | |
] | |
s.add(jack) | |
s.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment