__mapper_args__的SQLAlchemy类修饰 [英] SQLAlchemy Class Decoration for __mapper_args__

查看:278
本文介绍了__mapper_args__的SQLAlchemy类修饰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多类,这些类是我的数据库模式中多态性的一部分. 对于大多数人,我(需要)这样做:

I have a lot of classes which are part of polymorphism with my DB schema. With most of them I (need to) do:

__mapper_args__ = {'polymorphic_identity': unique_integer}
# unique_integer is a unique integer different for each class ex: 10

相反,我想使用装饰器,即:

Instead of this, I'd like to use a decorator, ie.:

@polid(10)
class ClassName(Inherited):
    # instead of repeating for each class the following:
    # __mapper_args__ = {'polymorphic_identity': 10}
    # I would like to have above decorator or something to do the trick.
    pass

我该怎么做?我需要使用哪种装饰器?以下内容不起作用(不注册):

How can I do this? What kind of decorator do I need to use? The following does not work (does not register):

def polid(v):
    def x(f):
        f.__mapper_args__ = {'polymorphic_identity': v}
        return f
    return x

推荐答案

到目前为止,也许更好,更神奇的解决方案可能是:

Perhaps a bit better, less magical solution attained so far could be:

def PID(value):
    ''' Mixin Class Generator For Polymorphic Identity Inheritance '''
    class MixinClassForPolymorphicIdentityInheritance: 
        __mapper_args__ = {'polymorphic_identity': value}
    return MixinClassForPolymorphicIdentityInheritance

用法:

class InheritingClass(PID(pidv), Parent): pass

(不幸的是)

这篇关于__mapper_args__的SQLAlchemy类修饰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆