gpt4 book ai didi

SQLAlchemy:declared_attr 列的外键

转载 作者:行者123 更新时间:2023-12-05 07:54:33 25 4
gpt4 key购买 nike

我在将 foreign_keys 参数与 declared_attr 列一起使用时遇到问题。我的模型看起来像这样:

class BasicTable(object):
created = db.Column(db.DateTime)
last_modified = db.Column(db.DateTime)

@declared_attr
def created_by_id(cls):
return db.Column(db.Integer, db.ForeignKey("app_user.id", use_alter = True, name='fk_created_by_id'))

@declared_attr
def created_by(cls):
return db.relationship("AppUser", foreign_keys='{}.{}'.format(cls.__tablename__, 'created_by_id'))

@declared_attr
def last_modified_by_id(cls):
return db.Column(db.Integer, db.ForeignKey("app_user.id", use_alter = True, name='fk_last_modified_by_id'))

@declared_attr
def last_modified_by(cls):
return db.relationship("AppUser", foreign_keys='{}.{}'.format(cls.__tablename__, 'last_modified_by_id'))

class AppUser(BasicTable, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64))
service_id = db.Column(db.Integer, db.ForeignKey("service.id"))

因为 BasicTable 中有两列引用了 AppUser,我遇到了“不明确的外键”错误,所以我尝试使用 foreign_keys 参数,如 here 所述.上面给了我这个错误:

AttributeError: 'Table' object has no attribute 'last_modified_by_id'

当我检查数据库时,该字段确实存在于所有使用 BasicTable 的表中。发生此错误是因为我引用了 declared_attr 列吗? This建议如此,但是当我尝试像这样使用 lambda 技术时:

foreign_keys=lambda: cls.created_by_id

我收到这个错误:

InvalidRequestError: When initializing mapper Mapper|AppUser|app_user, expression 'BasicTable' failed to locate a name ("name 'BasicTable' is not defined"). If this is a class name, consider adding this relationship() to the <class 'app.models.AppUser'> class after both dependent classes have been defined.

有解决办法吗?谢谢!

最佳答案

class BasicTable(object):
created = db.Column(db.DateTime)
last_modified = db.Column(db.DateTime)

@declared_attr
def created_by_id(cls):
return db.Column(db.Integer, db.ForeignKey("app_user.id", use_alter = True, name='fk_created_by_id'))

@declared_attr
def created_by(cls):
return db.relationship('AppUser', primaryjoin='%s.created_by_id==AppUser.id' % cls.__name__,
remote_side='AppUser.id')

@declared_attr
def last_modified_by_id(cls):
return db.Column(db.Integer, db.ForeignKey("app_user.id", use_alter = True, name='fk_last_modified_by_id'))

@declared_attr
def last_modified_by(cls):
return db.relationship('AppUser', primaryjoin='%s.last_modified_by_id==AppUser.id' % cls.__name__,
remote_side='AppUser.id')

关于SQLAlchemy:declared_attr 列的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31084037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com