Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join data from two tables in SQLAlchemy?

I have 3 tables: Account, User and Organization.

  • Account consists of id, name and organization_id.
  • User consists of email and organization_id.
  • Organization consists of id and name.

Each Account is registered to an Organization(through organization_id) and each User is registered to an Organization. The challenge is to display all the emails (from User) to the Account corresponding to the name whose organization_id matches the organization_id of User.

Here's my code till now:

class Account(db.Model):
    __tablename__ = "account"
    id = Column(Integer, primary_key=True)
    name = Column(String(50), index=True, unique=True)
    organization = Column(Integer, 
        ForeignKey("organization.id"),nullable=False, index=True)

class User(UserMixin, db.Model, RBACUserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    organization = Column(Integer, ForeignKey("organization.id"), 
                      nullable=False, index=True)

class Organization(db.Model):
    __tablename__ = "organization"
    id = Column(Integer, primary_key=True)
    name = Column(String(512))
    users = relationship("User", backref="organizations")
    accounts = relationship("Account", backref="organizations")
like image 264
Sujoy Roy Avatar asked May 31 '18 05:05

Sujoy Roy


People also ask

How do I create multiple tables in SQLAlchemy?

For this purpose, two tables are created in our SQLite database (college. db). The students table has the same structure as given in the previous section; whereas the addresses table has st_id column which is mapped to id column in students table using foreign key constraint.

What is Backref in SQLAlchemy?

The sqlalchemy backref is one of the type keywords and it passed as the separate argument parameters which has to be used in the ORM mapping objects. It mainly includes the event listener on the configuration attributes with both directions of the user datas through explicitly handling the database relationships.


1 Answers

Join user and account on organization id and filter based on name:

db.session.query(User.email).\
    join(Account, Account.organization == User.organization).\
    filter(Account.name == 'some name')

Query.join() allows passing arbitrary SQL expressions as the on-clause when using the 2 argument form.

like image 140
Ilja Everilä Avatar answered Oct 17 '22 00:10

Ilja Everilä