在Django中,我们可以使用非常简单的“选择”,例如:
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Foo(models.Model):
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
如何使用SQLAlchemy做这样的事情?
最佳答案
使用custom types。
例子:
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]
它的用法如下所示:
class Entity(Base):
__tablename__ = "entity"
height = Column(
ChoiceType({"short": "short", "medium": "medium", "tall": "tall"}), nullable=False
)
如果使用的是Python 3,则必须将iteritems()更改为items()。
关于python - SQLAlchemy-如何使用SQLAlchemy制作 “django choices”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6262943/