Flask SqlAlchemy join two models without foreign key MYSQL

前端 未结 4 2308
余生分开走
余生分开走 2021-02-20 11:49

I am joining two models without a foreign key:

Models:

class Users(db.Model):
    __tablename__ = \"Users\"
    userName = db.Column(db.String, primary_k         


        
相关标签:
4条回答
  • 2021-02-20 11:56

    To improve upon @Matt Healy's answer, if you also want to be able to access attributes on the joined object you can do something like:

    user, timeOff = db.session.query(Users, TimeOff).join(
        TimeOff, Users.userName == TimeOff.userName
    ).first()
    

    Then timeOff.dayWork etc. will give the information you need.

    0 讨论(0)
  • 2021-02-20 12:04

    Its an old post but I had a similar problem

    result = session.query(models.Users).join(models.TimeOff, models.Users.userName == models.TimeOff.userName).all()
    

    with this method, I can reach the features of the first object which is Users but not the TimeOff. I am wondering if it is possible to reach the secondary object's attributes. But I hope this helps.

    0 讨论(0)
  • 2021-02-20 12:15

    This worked for me, I have 3 tables, And I have the rtf_id which is unique to all three tables, you have to use the select_from keyword which tells the table starting from left.

    db_data = dbobj.session.query(A, B, C). \
    select_from(A).join(B, B.rtf_id == A.rtf_id). \
    join(C, C.rtf_id == A.rtf_id).all()
    
    0 讨论(0)
  • 2021-02-20 12:19

    You need to tell SQLAlchemy how to join the tables. Try something like this:

    result = db.session.query(Users).join(TimeOff,Users.userName==TimeOff.userName)
    
    0 讨论(0)
提交回复
热议问题