Count related items in a sqlalchemy model

送分小仙女□ 提交于 2020-01-04 09:16:08

问题


I'm trying to count the number of items in their respective categories and end up with a collection that I can iterate through in a jinja template. My final output is something like:

category1, 5

category2, 10

category3, 0

The zero items case is important.

My model is:

class Category(Base):

    __tablename__ = 'category'

    id = Column(Integer, primary_key=True)
    name = Column(String(80), unique=True)
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship(User)


class Item(Base):

    __tablename__ = 'item'

    id = Column(Integer, primary_key=True)
    name = Column(String(80))
    description = Column(String(500))
    category_id = Column(Integer, ForeignKey('category.id'))
    category = relationship(Category)
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship(User)
    date_added = Column(DateTime, default=datetime.datetime.now)

I have been kindly pointed in the direction of Stackoverflow: Counting relationships in SQLAlchemy, which led me to the query

count_categories = db_session.query(Category.name, func.count(Item.id)).join(Item.category).group_by(Category.id).all()

Which is almost correct, but it does not handle the zero case. When a category has zero items, I still need the category returned by the query.

Any help, much appreciated.


回答1:


Actually, I've figured it out:

count_categories = db_session.query(
        Category.name, func.count(Item.id)).outerjoin(
        Item).group_by(Category.id).all()

See SQLAlchemy documentation on Joins



来源:https://stackoverflow.com/questions/39040019/count-related-items-in-a-sqlalchemy-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!