3

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.

Community
  • 1
  • 1
Simon Otter
  • 173
  • 1
  • 3
  • 13
  • 1
    Possible duplicate of [Counting relationships in SQLAlchemy](http://stackoverflow.com/questions/25500904/counting-relationships-in-sqlalchemy) – Sergey Gornostaev Aug 19 '16 at 15:24

1 Answers1

2

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

Simon Otter
  • 173
  • 1
  • 3
  • 13