[英]SQLAlchemy query returns no data if a database field is empty
I have 2 tables: User and Groups 我有2个表:用户和组
The class declaration goes like this: 类声明如下:
class Groups(Base):
__tablename__ = 'groups'
group_id = Column(Integer, primary_key=True)
group_name = Column(Unicode(32))
user = relationship('User')
class User(Base):
__tablename__ = 'user'
user_id = Column(Integer, primary_key=True)
name = Column(Unicode(64))
email = Column(Unicode(64))
group_id = Column(Integer, ForeignKey('groups.group_id'))
So a group ID can have multiple user_id's attached to it. 因此,一个组ID可以附加多个user_id。
Now, I'm trying to query the above tables like this: 现在,我试图像这样查询以上表格:
user_list_incomplete1 = DBSession.query(User.name, User.user_id, Groups.group_name).filter(User.group_id == Groups.group_id).order_by(User.user_id).all()
The query works for those users which have a group id declared but returns nothing (empty list) if that field is empty. 该查询适用于声明了组ID但如果该字段为空则不返回任何内容(空列表)的那些用户。
How should I write the query in order to obtain the data even for those User rows that don't have a group id? 我应该如何编写查询以获取数据,即使对于没有组ID的用户行也是如此?
The relationship you defined will result in an inner join by default. 默认情况下,您定义的关系将导致内部联接 。 What you want here is an outer join
您想要的是外部联接
Something like: 就像是:
user_list_incomplete1 = DBSession.query(User.name, User.user_id, Groups.group_name)\
.outerjoin(Groups)\
.filter()... etc
Make sense? 说得通? An outer join will show all records of both tables regardless if there is a foreign key match.
外部联接将显示两个表的所有记录,无论是否有外键匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.