SQLAlchemy:如何根据列的后端有条件地选择列的类型 [英] SQLAlchemy: How to conditionally choose type for column by depending on its backend
问题描述
我想使用 HSTORE
如果使用PostgreSQL作为后端,则输入列,或者
I want to use HSTORE
type for a column if it uses PostgreSQL as its backend, or PickleType
otherwise. The problem is that we cannot determine which backend will be used when schema is being defined (in Python). How can I determine this and conditionally choose the data type when the table actually is created on the backend database?
推荐答案
You can accomplish something like this with TypeEngine.with_variant
:
from sqlalchemy.types import PickleType
from sqlalchemy.dialects import postgresql
HybridType = PickleType()
HybridType = HybridType.with_variant(postgresql.HSTORE(), 'postgresql')
这会创建一个新类型HybridType
,您可以像使用其他任何类型一样使用它,但要注意的是它将在Postgres上生成一个HSTORE
列,并在其他任何地方生成一个PickleType
.
This creates a new type, HybridType
, which you can use like any other type, with the caveat that it will produce an HSTORE
column on Postgres and a PickleType
everywhere else.
这篇关于SQLAlchemy:如何根据列的后端有条件地选择列的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!