SQLAlchemy and joins, we have no foreign keys

前端 未结 1 1580
故里飘歌
故里飘歌 2021-02-15 15:15

Assume the following in MySQL:

CREATE TABLE users (
  id integer auto_increment primary key,
  username varchar(30),
  active enum(\'N\',\'Y\'),
  created_on int         


        
1条回答
  •  不知归路
    2021-02-15 15:58

    You have two options. You can pass the join condition in join like so:

    j = join(users, comments, onclause=users.c.id == commends.c.user_id)
    

    If you're defining this in terms of a orm.relationship property, the keyword parameter will be primaryjoin instead of onclause.

    However, the approach I Prefer is to just lie. Inform SQLAlchemy that there is a foreign key, even though there is not. 

    comments = Table('comments', metadata,
        Column('id', Integer, primary_key=True),
        Column('user_id', Integer, ForeignKey('users.id')),
        ...
    )
    

    SQLAlchemy will the proceed as if the foreign key were in fact present, even though the actual database doesn't have that. Of course, you may run into trouble if the implied foriegn key constraint is violated (comments.user_id when there's no corresponding users.id), but you'd probably be in trouble anyway.

    0 讨论(0)
提交回复
热议问题