python SQLAlchemy外键类装饰器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python SQLAlchemy外键类装饰器相关的知识,希望对你有一定的参考价值。

def foreign_key(table):
    """class decorator, add a foreign key to a sqlalchemy model.
    parameter table is the destination table, in a one-to-many relationship, table is the "one" side.
    """

    def ref_table(cls):
        setattr(cls, '{0}_id'.format(table), db.Column(db.String(50), db.ForeignKey('{0}.id'.format(table))))
        setattr(cls, table,
                db.relationship(table.capitalize(), backref=db.backref(cls.__name__.lower() + 's', lazy='dynamic')))
        return cls

    return ref_table


# Quick Start
@foreign_key('user')
class Company(db.Model, Base):
    name = db.Column(db.Boolean, default=False)

以上是关于python SQLAlchemy外键类装饰器的主要内容,如果未能解决你的问题,请参考以下文章