SQLAlchemy, how to filter by empty array column?

Question:

I have that kind of Model in SQLAlchemy:

class MyModel(Base):
    __tablename__ = 'my_models'
    name = Column(String(255), nullable=False)
    company_ids = Column(ARRAY(Integer), nullable=True)

I have intentionally created models with empty arrays and try to query them like this:

db.query(MyModel).filter(~MyModel.company_ids.any())

Which doesn’t return anything.

Is it possible to filter models that have empty array field?

============UPDATE===============

I was able to query it by using this method:

db.query(MyModel).filter(MyModel.company_ids == '{}')

However I think it is only PostgreSQL specific answer

Asked By: Mr.D

||

Answers:

I was able to query it by using this method:

db.query(MyModel).filter(MyModel.company_ids == '{}')

However I think it is only PostgreSQL specific answer

Answered By: Mr.D

I think SQLAlchemy’s way of doing this is

db.query(MyModel).filter(
 func.cardinality(MyModel.company_ids == 0)
)
Answered By: kartikey rajvaidya
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.