SQLAlchemy – include rows where func.count() called on many-many relationship results in 0

I am querying a table Team to get a list of all the teams. This query object is fed to a pagination function that makes use of sqlalchemy’s paginate().

The function takes inputs for order and order_by which determine the column and order of the resulting query. This works fine when the sort is performed directly on one of Team‘s attributes, but I also want to perform the sort on the count of the number of relationships each record has with another table Player.

Using func.count(), .join() and .group_by() this is possible – however if a team does not have any players recorded, the record is ommitted from the query. I want to include all results in this query.

I have thought of creating a second query that omits the results of the first one, and then combine them somehow before passing them to the paginate function, but I haven’t been able to find a way to do this.

Is there a way to include the results where count should return 0, or is there another way to achieve this effect?

The function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def get_teams(filters):
"""Get the collection of all teams"""
page = filters['page']
per_page = filters['per_page']
order = filters['order'] # validates as either 'asc' or 'desc'
order_by = filters['order_by']
if order_by == 'active_players': # checks if sort needs to be done manually
query = db.session.query(Team, sa.func.count(PlayerTeam.id).label('count'))
.join(Team.player_association)
.filter(PlayerTeam.end_date == None)
.group_by(Team)
.order_by(getattr(sa, order)('count'))
else: # sort is directly on attribute, this is easy
query = sa.select(Team).order_by(getattr(sa, order)(getattr(Team, order_by)))
return Team.to_collection_dict(query, page, per_page)
</code>
<code>def get_teams(filters): """Get the collection of all teams""" page = filters['page'] per_page = filters['per_page'] order = filters['order'] # validates as either 'asc' or 'desc' order_by = filters['order_by'] if order_by == 'active_players': # checks if sort needs to be done manually query = db.session.query(Team, sa.func.count(PlayerTeam.id).label('count')) .join(Team.player_association) .filter(PlayerTeam.end_date == None) .group_by(Team) .order_by(getattr(sa, order)('count')) else: # sort is directly on attribute, this is easy query = sa.select(Team).order_by(getattr(sa, order)(getattr(Team, order_by))) return Team.to_collection_dict(query, page, per_page) </code>
def get_teams(filters):
    """Get the collection of all teams"""
    page = filters['page']
    per_page = filters['per_page']
    order = filters['order']  # validates as either 'asc' or 'desc'
    order_by = filters['order_by']

    if order_by == 'active_players':  # checks if sort needs to be done manually
        query = db.session.query(Team, sa.func.count(PlayerTeam.id).label('count')) 
            .join(Team.player_association) 
            .filter(PlayerTeam.end_date == None) 
            .group_by(Team) 
            .order_by(getattr(sa, order)('count'))
    else:  # sort is directly on attribute, this is easy
        query = sa.select(Team).order_by(getattr(sa, order)(getattr(Team, order_by)))

    return Team.to_collection_dict(query, page, per_page)

Models:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Team(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=True, unique=True, nullable=False)
# some other fields
player_association = db.relationship('PlayerTeam', back_populates='team',lazy='dynamic')
players = association_proxy('player_association', 'player')
@staticmethod
def to_collection_dict(query, page, per_page):
resources = db.paginate(query, page=page, per_page=per_page, error_out=False)
# convert resources to dict and return
class Player(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_name = db.Column(db.String(64), nullable=False)
# some other fields
team_association = db.relationship('PlayerTeam', back_populates='player', lazy='dynamic')
teams = association_proxy('team_association', 'team')
class PlayerTeam(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, db.ForeignKey('player.id'))
team_id = db.Column(db.Integer, db.ForeignKey('team.id'))
end_date = db.Column(db.DateTime)
# some other fields
player = db.relationship('Player', back_populates='team_association')
team = db.relationship('Team', back_populates='player_association')
</code>
<code>class Team(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True, nullable=False) # some other fields player_association = db.relationship('PlayerTeam', back_populates='team',lazy='dynamic') players = association_proxy('player_association', 'player') @staticmethod def to_collection_dict(query, page, per_page): resources = db.paginate(query, page=page, per_page=per_page, error_out=False) # convert resources to dict and return class Player(db.Model): id = db.Column(db.Integer, primary_key=True) player_name = db.Column(db.String(64), nullable=False) # some other fields team_association = db.relationship('PlayerTeam', back_populates='player', lazy='dynamic') teams = association_proxy('team_association', 'team') class PlayerTeam(db.Model): id = db.Column(db.Integer, primary_key=True) player_id = db.Column(db.Integer, db.ForeignKey('player.id')) team_id = db.Column(db.Integer, db.ForeignKey('team.id')) end_date = db.Column(db.DateTime) # some other fields player = db.relationship('Player', back_populates='team_association') team = db.relationship('Team', back_populates='player_association') </code>
class Team(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True, nullable=False)
    # some other fields

    player_association = db.relationship('PlayerTeam', back_populates='team',lazy='dynamic')
    players = association_proxy('player_association', 'player')

    @staticmethod
    def to_collection_dict(query, page, per_page):
        resources = db.paginate(query, page=page, per_page=per_page, error_out=False)
        # convert resources to dict and return

class Player(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    player_name = db.Column(db.String(64), nullable=False)
    # some other fields

    team_association = db.relationship('PlayerTeam', back_populates='player', lazy='dynamic')
    teams = association_proxy('team_association', 'team')

class PlayerTeam(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    player_id = db.Column(db.Integer, db.ForeignKey('player.id'))
    team_id = db.Column(db.Integer, db.ForeignKey('team.id'))
    end_date = db.Column(db.DateTime)
    # some other fields

    player = db.relationship('Player', back_populates='team_association')
    team = db.relationship('Team', back_populates='player_association')

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật