In Django we can use very simple "choices" e.g.:
GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) class Foo(models.Model): gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
How to make something like this using SQLAlchemy?
Both Django and SQLAlchemy can be used with MySQL, PostgreSQL, Oracle and SQLite. If you're using MSSQL, you should go for SQLAlchemy, as it's fully supported by it and you'll find more information and documentation about it.
To select data from a table via SQLAlchemy, you need to build a representation of that table within SQLAlchemy. If Jupyter Notebook's response speed is any indication, that representation isn't filled in (with data from your existing database) until the query is executed. You need Table to build a table.
SQLAlchemy is great because it provides a good connection / pooling infrastructure; a good Pythonic query building infrastructure; and then a good ORM infrastructure that is capable of complex queries and mappings (as well as some pretty stone-simple ones).
What is Flask-SQLAlchemy? Flask-SQLAlchemy is an extension for Flask that aims to simplify using SQLAlchemy with Flask by providing defaults and helpers to accomplish common tasks. One of the most sought after helpers being the handling of a database connection across the app.
Use custom types.
Example:
import sqlalchemy.types as types class ChoiceType(types.TypeDecorator): impl = types.String def __init__(self, choices, **kw): self.choices = dict(choices) super(ChoiceType, self).__init__(**kw) def process_bind_param(self, value, dialect): return [k for k, v in self.choices.iteritems() if v == value][0] def process_result_value(self, value, dialect): return self.choices[value]
The use of it would look like:
class Entity(Base): __tablename__ = "entity" height = Column( ChoiceType({"short": "short", "medium": "medium", "tall": "tall"}), nullable=False )
If you are using Python 3, you have to change iteritems() to items().
I would probably go for sqlalchemy_utils
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With