Created
December 5, 2017 23:06
-
-
Save boaf/48612f36a111df3a7306e41653bf790f to your computer and use it in GitHub Desktop.
SQLAlchemy snippets
This file contains hidden or 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 import Column, Integer, String, Index | |
from sqlalchemy.ext.declarative import declarative_base | |
Base = declarative_base() | |
class Person(Base): | |
__tablename__ = 'person' | |
id = Column(Integer, primary_key=True, autoincrement=True) | |
first_name = Column(String(64), index=True) # A single-column index | |
last_name = Column(String(64), index=True) | |
email = Column(String(64)) | |
# Yes, String(64) is probably not a good data type for these columns | |
Index('email_name_idx', Person.email, Person.first_name) | |
# Equates to: | |
# CREATE TABLE `person` ( | |
# `id` INT(11) NOT NULL AUTOINCREMENT, | |
# `first_name` VARCHAR(64) DEFAULT NULL, | |
# `last_name` VARCHAR(64) DEFAULT NULL, | |
# `email` VARCHAR(64) DEFAULT NULL, | |
# PRIMARY KEY (`id`), | |
# KEY `first_name` (`first_name`), | |
# KEY `last_name` (`last_name`), | |
# KEY `email_name_idx` (`email`, `first_name`), | |
# ) ...; |
This file contains hidden or 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 import Column, Integer | |
from sqlalchemy.ext.declarative import declarative_base | |
Base = declarative_base() | |
class Person(Base): | |
__tablename__ = 'person' | |
__table_args__ = { | |
'mysql_engine': 'InnoDB', | |
'mysql_default_charset': 'utf8mb4' | |
} | |
id = Column(Integer, primary_key=True, autoincrement=True) | |
# Equates to: | |
# CREATE TABLE `person` ( | |
# `id` INT(11) NOT NULL AUTOINCREMENT, | |
# PRIMARY KEY (`id`) | |
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment