Bogdan Rosciuc Bogdan Rosciuc - 1 month ago 12
Python Question

SQLAlchemy query returns no data if a database field is empty

I have 2 tables: User and Groups

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.

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.

How should I write the query in order to obtain the data even for those User rows that don't have a group id?

Answer

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.

Comments