简体   繁体   English

具有相同名称的复合键的SQLAlchemy部分索引

[英]SQLAlchemy Partial Index with composite keys having the same name

I am using Python 2.7 and SQLAlchemy 0.9.8 and trying to use partial indexes. 我正在使用Python 2.7和SQLAlchemy 0.9.8,并尝试使用部分索引。

I have two tables (just the relevant part) 我有两个表(只是相关部分)

class DesignerRange
    __tablename__ = 'designer_ranges'  
    shortcode = Column(Unicode(12))  

class Design
    __tablename__ = 'designs'  
    shortcode = Column(Unicode(12))
    designer_range_id = Column(
        Integer,
        ForeignKey('designer_ranges.id'),
        nullable=False,
     )
    designer_range = relationship(
        DesignerRange,
        backref=backref(
        'designs',
        single_parent=True,
    ),
    lazy='joined',
)  

And I want to create a partial Index that when the shortcode of the Design is not null (it exists) it should be unique within the DesignerRange. 我想创建一个局部索引,当Design的短代码不为null(它存在)时,它在DesignerRange中应该是唯一的。

I am trying something like this 我正在尝试这样的事情

 @declarative.declared_attr
 def __table_args__(cls):
     return ( 
            Index('design_shortcode',
                table('designer_ranges', column('shortcode')).c.shortcode,
                cls.shortcode, unique=True,
                postgresql_where=(cls.shortcode!=None)),
            )

This is the resulting Alembic migration 这就是由此产生的Alembic迁移

op.create_index('design_shortcode', 'designs', ['shortcode', 'shortcode'], unique=True, postgresql_where=sa.text('designs.shortcode IS NOT NULL'))

But I am getting this warning 但是我得到这个警告

sqlalchemy/sql/base.py:508: SAWarning: Column 'shortcode' on table <sqlalchemy.sql.selectable.TableClause at 0x7f50a1768550; designer_ranges> being replaced by Column('shortcode', Unicode(length=12), table=<designs>), which has the same key.  Consider use_labels for select() statements.

I've no idea where to apply use_labes in this case, it seems to exist only within a select clause. 在这种情况下,我不知道在哪里应用use_labes,它似乎仅存在于select子句中。 Thanks 谢谢

I've solved my problem by using 我已经通过使用解决了我的问题

@declarative.declared_attr
def __table_args__(cls):
    return (
    Index('design_shortcode_idx',
            cls.designer_range_id,
            cls.shortcode, unique=True,
            postgresql_where=(cls.shortcode!=None)),
)

So, instead of trying to get the shortcode from the foreign key table I am just getting its unique id. 因此,与其尝试从外键表中获取简码,不如获取其唯一ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM