简体   繁体   English

Flask Sqlalchemy:用外键查询数据库

[英]Flask Sqlalchemy: Query a database with a foreign key

I am still learning flask sqlalchemy but am working on a dashboard using flask, mysql workbench, and sqlalchemy. I am still learning flask sqlalchemy but am working on a dashboard using flask, mysql workbench, and sqlalchemy. I would like to query two tables:我想查询两个表:

class User(db.Model):
    id = Column(Integer(), primary_key=True)
    name = Column(String(200))
    first_name = Column(String(200))

class Certificates(db.Model):
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey("user.id", 
    ondelete="CASCADE"))
    report_sent = Column(Boolean, default=False)
    delivery_time = Column(DateTime)
    certificate_type = Column(String(32))

I would like to know the total number of users that has a certificate我想知道拥有证书的用户总数

I tried:我试过了:

user_with_cert = db.session.query(func.count(User.id)).filter(Certificates.certificate_type != None).filter(Certificates.user_id == User.id).all()

The query above returned the total number of records in the Certificate table not the actual number of users with a certificate.上面的查询返回的是证书表中的记录总数,而不是实际持有证书的用户数。

I also tried:我也试过:

user_cert = (
            db.session.query(User, Certificates)
            .join(Certificates)
            .all()
        )

        for user, cert in b2c_cert:
            t = db.session.query(func.count(user.id)).filter(
                cert.user_id == user.id).filter(cert.certificate_type != None).all()
            print(t)

Please how can I achieve this goal?请问我怎样才能实现这个目标?

You need to use db.relationship('Child table', backref='parent') on your parent table where the backref property identifies the parent table.您需要在 backref 属性标识父表的父表上使用 db.relationship('Child table', backref='parent') 。 And db.ForeignKey(table.primary_key) class on the column from your child table.并且 db.ForeignKey(table.primary_key) class 在您的子表的列上。

Example:例子:

class User(db.Model):
    id = Column(Integer(), primary_key=True)
    name = Column(String(200))
    first_name = Column(String(200))
    certificates = db.relationship('Certificates', backref='user')

class Certificates(db.Model):
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.id', 
    ondelete="CASCADE"))
    report_sent = Column(Boolean, default=False)
    delivery_time = Column(DateTime)
    certificate_type = Column(String(32))

Then you can just use然后你可以使用

db.session.query(Certifiates).filter(Certifiates.user_id == user.id).all()

to get the results (I think that's the correct condition, it may not be that way).得到结果(我认为这是正确的条件,可能不是那样)。

So I modified my table by adding a db.relationship to backref the parent in the parent table:所以我通过添加一个 db.relationship 来修改我的表来反向引用父表中的父级:

class User(db.Model):
    id = Column(Integer(), primary_key=True)
    name = Column(String(200))
    first_name = Column(String(200))
    certificates = db.relationship('Certificates', backref='user')

Present record in the Certificates.user_id is (1, 1, 2, 1, 2): I think the total number of record is 5 but the total number of users with certificate is 2 So I ran this query which gave me a distinct number of users with certificates: Certificates.user_id 中的当前记录是 (1, 1, 2, 1, 2):我认为记录的总数是 5,但拥有证书的用户总数是 2 所以我运行了这个查询,它给了我一个不同的数字拥有证书的用户:

users_with_cert = db.session.query(Certificates.user_id).distinct().count()

Please suggestions are welcomed, cos am thinking this query is right but only for the users assigned to a Certificates, maybe not necessarily the users with a certificate欢迎提出建议,因为我认为此查询是正确的,但仅适用于分配给证书的用户,可能不一定是拥有证书的用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM