Search code examples
pythonormsqlalchemyforeign-keys

SQLAlchemy - querying multiple tables and returning nested objects


Suppose we have a simple one-to-many relationship between Company and Employee, is there a way to query all companies and have a list of employees in the attribute of each company?

class Company(Base):
    __tablename__ = 'company'

    id = Column(Integer, primary_key=True)
    name = Column(String)


class Employee(Base):
    __tablename__ = 'employee'

    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)
    company_id = Column(Integer, ForeignKey(Company.id))

I'm looking for something like this:

>>> result = db.session.query(Company).join(Employee).all()
>>> result[0].Employee
[<Employee object at 0x...>, <Employee object at 0x...>]

The size of result should be same as the number of rows in company table.

I tried the following and it gives tuple of objects (which makes sense) instead of nice parent / child structure:

>>> db.session.query(Company, Employee).filter(Company.id = Employee.company_id).all()

It's not hard to convert this into my desired object structure but just wanted to see if there's any shortcut.


Solution

  • You could do something like this:

    class Company(Base):
        __tablename__ = 'company'
    
        id = Column(Integer, primary_key=True)
        name = Column(String)
    
        employees = db.session.query(Company, Employee).filter(Company.id = self.id).all()
        self.employee_list = ['{0} {1}'.format(c.first_name, c.last_name) for c in employees]
    

    Then you could access a employee name with Company.employee_list[0]