Skip to main content
 首页 » 编程设计

python之__table_args__ 的 Sqlalchemy 声明式继承

2024年10月25日11zhenyulu

假设我有这样的表

class Base(object): 
    id = Column(Integer, primary_key=True) 
    date_updated = Column(Date, nullable=True) 
    rating = Column(Integer, nullable=False, default=0) 
    status = Column(SmallInteger, nullable=False, default=0) 
 
    @declared_attr 
    def __tablename__(cls): 
        return "table_%s" % cls.LANG 
 
    @declared_attr 
    def __table_args__(cls): 
        return ( 
            Index('ix__%s__rating' % cls.__tablename__, 'rating'), 
            Index( 
                'ix__%s__status' % cls.__tablename__, 
                'status', 
                postgresql_where=column('status') == 0, 
            ), 
            Index( 
                'ix__%s__date_updated' % cls.__tablename__, 
                'date_updated', 
                postgresql_where=column('date_updated') != None, 
            ), 
        ) 
 
   class TableEn(Base, db.Model): 
       LANG = 'en' 
 
 
   class TableUk(Base, db.Model): 
       LANG = 'uk' 

我找到了如何在父 __table_args__ 中创建诸如 status 和 date_updated 之类的(部分)索引。

但我需要创建desc排序索引rating,比如func.desc(rating),但我不知道该怎么做那。

没有一个变体对我有用(变体和它的错误):

  • Index('ix__%s__rating' % cls.__tablename__, 'rating desc')

    KeyError: 'rating desc'

  • Index('ix__%s__rating' % cls.__tablename__, cls.rating.desc())

    sqlalchemy.exc.ArgumentError: 无法将未命名的列添加到列集合

  • Index('ix__%s__rating' % cls.__tablename__, desc('rating'))

    在数据库中创建模式时

    sqlalchemy.exc.ProgrammingError: (ProgrammingError) ")"处或附近的语法错误 第 1 行:在 table_en () 上创建索引 ix__table_en__rating

当然,我可以使用直接 SQL 手动创建该索引,但我确信某处存在解决方案。

提前致谢!

请您参考如下方法:

这里简化了代码,做你想做的事:

class BaseModel(Base): 
 
    __abstract__ = True 
 
    id = Column(Integer, primary_key=True) 
    rating = Column(Integer, nullable=False, default=0) 
 
    @declared_attr 
    def __tablename__(cls): 
        return "table_%s" % cls.LANG 
 
    @classmethod 
    def build_indexes(cls): 
        Index('ix__%s__rating' % cls.__tablename__, cls.__table__.c.rating.desc()) 
 
 
@event.listens_for(BaseModel, 'instrument_class', propagate=True) 
def receive_mapper_configured(mapper, class_): 
    class_.build_indexes() 
 
 
class TableEn(BaseModel): 
   LANG = 'en' 
 
 
class TableUk(BaseModel): 
   LANG = 'uk' 

完整代码 here .

这里有 2 个问题。首先,您应该针对表列而不是映射器对象属性调用 desc。但是如果你这样做,你就会遇到问题,因为 __table__ 属性是在从 __table__args__ 获取信息后创建的。所以你需要在创建 __table__ 字段后创建索引。一种方法是通过 sqlalchemy 事件。