Nuru Salihu
Nuru Salihu

Reputation: 4928

column "Column" must appear in the GROUP BY clause -- SQLAlchemy

Please why do i get titled error despite the fact that my the said column in mentioned in group_by. Below is my query

products = session
               .query(User) \
               .join(User.products) \
               .join(Product.productitems) \
               .values( Product.title.label('title'),(func.count(ProductItem.id)).label('total')) \
               .group_by(Product.id,Product.title) \
               .order_by(Product.created_date)

model classes

class User(UserMixin , Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    title = Column(CHAR(3), nullable = True)

class Product(Base):
    __tablename__ = 'products'
    id = Column(Integer, primary_key =True)
    title = Column(String(250), nullable = False)
    ..
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship('User',backref=backref("products", cascade="all, delete-orphan"),lazy='joined')

class ProductItem(Base):
    __tablename__ ='product_items'
    id = Column(Integer , primary_key = True)
    ...
    product_id = Column(Integer, ForeignKey('products.id'))
    product = relationship('Product',backref=backref("productitems", cascade="all, delete-orphan"),lazy='joined' )

From the console, i can see the query return

SELECT 
    products.title AS title
   ,COUNT(product_items.id) AS total 
FROM 
    users 
        JOIN products ON users.id = products.user_id 
        JOIN product_items ON products.id = product_items.product_id

Then break with an error on the group_by. Please what is it asking for ? Any help would be appreciated.

Upvotes: 8

Views: 5701

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180987

SQLalchemy requires values to be the last thing in the chain since it doesn't return a query to continue. What you need to do is probably something like (the untested);

products = session.query(User)                                               \
                  .join(User.products)                                       \
                  .join(Product.productitems)                                \
                  .group_by(Product.id, Product.title, Product.created_date) \
                  .order_by(Product.created_date)                            \
                  .values( Product.id.label('id'),                           \
                           Product.title.label('title'),                     \      
                           (func.count(ProductItem.id)).label('total')) 

Upvotes: 7

Related Questions