将__table_args__与SQLAlchemy中的mixin类的约束相结合

时间:2014-05-01 20:03:01

标签: python orm sqlalchemy declarative

在SQLAlchemy中,我已经阅读了如何在声明声明时组合来自不同mixin的__table_args__

Combining Table/Mapper Arguments from Multiple Mixins

我遇到的问题是,该示例显示了如何在链的末尾(MRO中的最终类)完成此操作,但是如果我有这些Mixins并希望它发生在MyClientMixinBase类,以避免为其他类型的mixin重复此代码?

class LaneCarrierCommitmentSummaryMixin(object):
    """ Lane Carrier Commitment Summary.

    A base class for LCCS to mixin with a client specific class.
    """

    __tablename__ = 'lane_carrier_commitment_summary'
    __table_args__ = ((UniqueConstraint(['hashmap_key', 'bow'],
                                        name='uq_lane_carrier_commitment_summary_hashmap_key_bow')),)

class MyClientMixin(object):
    """ MyClient Mixin class for providing the ETL schema. """

    __table_args__ = {'schema': 'myclient_etl'}

class MyClientLaneCarrierCommitmentSummary(LaneCarrierCommitmentSummaryMixin, DateTrackedMixin, MyClientMixin, Base):
    pass

我对这个概念感到苦苦挣扎。

1 个答案:

答案 0 :(得分:8)

此基类将搜索要添加的__table_args__的所有mixins,然后检查要添加的__local_table_args__的当前类。这样,__local_table_args__不会与声明的attr发生冲突。基类(cls.mro())以相反的顺序检查,以便链中较低的mixins被更高的mixin覆盖。

def _process_args(cls, attr, out_args, out_kwargs):
    try:
        args = getattr(cls, attr)
    except AttributeError:
        return

    if isinstance(args, Mapping):  # it's a dictionary
        out_kwargs.update(args)
    else:  # it's a list
        if isinstance(args[-1], Mapping):  # it has a dictionary at the end
            out_kwargs.update(args.pop())

        out_args.extend(args)

class Base():
    @declared_attr
    def __mapper_args__(cls):
        args = []
        kwargs = {}

        for mixin in reversed(cls.mro()):
            _process_args(mixin, '__mapper_args__', args, kwargs)

        _process_args(mixin, '__local_mapper_args__', args, kwargs)

        return kwargs  # mapper only takes dict

    @declared_attr
    def __table_args__(cls):
        args = []
        kwargs = {}

        for mixin in reversed(cls.mro()):
            _process_args(mixin, '__table_args__', args, kwargs)

        _process_args(cls, '__local_table_args__', args, kwargs)

        args.append(kwargs)  # [item, item, ...,  kwargs]
        return tuple(args)

所有mixin都应该正常定义__table_args__,但是继承自Base的“真实”类应该定义__local_table_args__