Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - How to make "django choices" using SQLAlchemy?

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?

like image 420
pmoniq Avatar asked Jun 07 '11 09:06

pmoniq


People also ask

Can SQLAlchemy be used with Django?

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.

How do I select data in SQLAlchemy?

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.

Is SQLAlchemy worth learning?

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).

Is flask-SQLAlchemy the same as SQLAlchemy?

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.


2 Answers

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().

like image 186
estin Avatar answered Sep 18 '22 18:09

estin


I would probably go for sqlalchemy_utils

like image 40
radeklos Avatar answered Sep 20 '22 18:09

radeklos