简体   繁体   中英

SQLalchemy to get data from multiple table in single object

I have 3 tables, users , projects and project_users is_admin table and I am trying to write ORM to get data from them.

My Models are here: https://pastebin.com/ZrmhKyNL

In simple SQL, we could join and select particular columns and get the desired output. But in ORM when I write query like this:

sql = """ select * from 
            projects p, users u, projects_users pu 
            where
            p.name = '%s' and
            p.id = pu.project_id and 
            pu.user_id = u.id and
            p.is_active = true and 
            u.is_active = true 
        """ % project_name

and it works well and returns response in this format:

[ { All columns of above 3 tables. } ]

But when I try to convert this to sqlalchamey ORM, it doesn't work well:

return (
        db.query(User)
        .filter(Project.id == ProjectsUser.project_id)
        .filter(ProjectsUser.user_id == User.id)
        .filter(Project.is_active == True)
        .filter(User.is_active == True)
        .filter(Project.name == project_name)
        .all()
    )

I want is_admin value to be returned along with user object. This seems very common use case, but I couldn't find any solution related to SQLalchemy ORM.

If this is a one-to-one relationship, meaning that for every user you can have one and only one entry in the admin table, you could add a column to serve as back-reference:

class User(Base):
    id = ...
    name = ...
    last_login = ...
    admin = relationship("Admin", uselist=False, back_populates="user")

class Admin(Base):
    id = ...
    is_admin = ...
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship("User", back_populates="admin")

Then you can query only the table user, and access the values from the relationship via user.admin.is_admin .

Read more:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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