首页 > 解决方案 > 如何使用外键使用 SQLAlchemy 和 Flask 查询我的数据库

问题描述

我正在尝试根据执行某些测试的站点来计算数据库中的记录数。测试站点通过外键链接到测试详细信息表。我需要使用外键的值(TestSite“站点”列,而不是“id”列)来查询 Cat1Tests 表(使用 SQLalchemy)并返回在任何给定站点执行的测试数量。如果我为我感兴趣的站点提供 id,我可以成功生成在一个站点上执行的测试计数,但这并不是我正在寻找的实现。

我的模型如下所示:

    __tablename__="testsite"
    id = Column(Integer, primary_key=True)
    site = Column(String(120), unique=True)
    cat1tests = db.relationship('Cat1Tests', backref='testsite', lazy=True)
    cat2tests = db.relationship('Cat2Tests', backref='testsite', lazy=True)
    record_updated = Column(DateTime, onupdate=func.current_timestamp()) 
    
def __init__(self, site, cat1tests, cat2tests, record_updated):
        self.id = id
        self.site = site
        self.cat1tests = cat1tests
        self.cat2tests = cat2tests
        self.record_updated = record_updated


class Cat1Tests(db.Model):
    __tablename__ = "cat1tests"
    id = Column(Integer, primary_key=True)
    test_id = Column(String(80))
    foo = Column(Integer, db.ForeignKey('cat1foo.id'))
    bar = Column(Integer, db.ForeignKey('cat1bar.id'))
    baz = Column(Integer, db.ForeignKey('cat1baz.id'))
    testsite_id = Column(Integer, db.ForeignKey('testsite.id'))

def __init__(self, test_id, foo, bar, baz, testsite_id)
        self.test_id = test_id
        self.foo = foo_id
        self.bar = bar_id
        self.baz = baz_id


class Cat2Tests(db.Model):
    __tablename__ = "cat2tests"
    id = Column(Integer, primary_key=True)
    test_id = Column(String(80))
    foo = Column(Integer, db.ForeignKey('cat2foo.id'))
    bar = Column(Integer, db.ForeignKey('cat2bar.id'))
    baz = Column(Integer, db.ForeignKey('cat2baz.id'))
    testsite_id = Column(Integer, db.ForeignKey('testsite.id'))

def __init__(self, test_id, foo, bar, baz, testsite_id)
        self.test_id = test_id
        self.foo = foo_id
        self.bar = bar_id
        self.baz = baz_id
        self.testsite = testsite_id

    def __repr__(self):
        return '{}'.format(self.test_id)

我想在我的应用程序主页上的表格中显示此计数以及每个类别(在任何站点)中的测试总数,我的路线(视图)如下所示:

@bp.route('/')
def home(): 
    #static template file "/" 
    cat1testcount=db.session.query(func.count(Cat1Tests.id)).scalar()
    cat2testcount=db.session.query(func.count(Cat2Tests.id)).scalar()

    data = {
        "cat1testcount" : cat1testcount,
        "cat2testcount" : cat2testcount,
    }

我可以通过使用得到正确的结果

cat1sitetestcount=db.session.query(func.count(Cat1Tests.id)).filter(Cat1Tests.testsite_id==7).scalar()

然后将 cat1sitetestcount 添加到数据字典中。但是 testsite 表中的 ID 不像站点名称那样可访问。
我已经尝试按照此处所述实现表连接:Join and count in sql-alchemy

sitecat1tests= (db.session.query(Cat1Tests, func.count(TestSite.id)).select_from(Cat1Tests).join(TestSite.id).group_by(RCat1Tests.testsite))

但我收到一个错误: sqlalchemy.exc.ArgumentError: Join target TestSite.id does not refer to a mapped entity

请问有人可以让我知道我还能尝试什么吗?

标签: flasksqlalchemyflask-sqlalchemy

解决方案


推荐阅读