0

I have a simple One-to-Many relation mapped with SqlAlchemy:

Base = declarative_base()

class Type(Base):

    __tablename__ = "entity_types"

    type = Column(String(100), primary_key=True)
    description = Column(String(300))

class Entity(Base):

    __tablename__ = "entities"

    id = Column(Integer, primary_key=True)
    type_id = Column('type', String(100), ForeignKey(Types.type), 
                     nullable=False)
    type = relation(Type, backref='entities')
    value = Column(Text, nullable=False)

I want to query all types ever used in an entity. In pure SQL I would accomplish this by:

SELECT entity_types.*
FROM entities
    JOIN entity_types ON entities.type == entity_types.type
GROUP BY entity_types.type

How do I solve this using SqlAlchemy's ORM-Engine?

I've tried these queries, but they all don't return what I want:

session.query(Action.type).group_by(Action.type).all()

session.query(Type).select_from(Action).group_by(Type).all()

I've also tried using options(joinedload('type')), but I found out, this is only used to force eager loading and to bypass lazy-loading.

ADDITION: I've just added the backref in the relation of Entity. I think the problem is solvable by querying count(Type.entities) > 0, but I cannot figure out how to exactly form a valid ORM query.

1 Answer 1

1

I've just figured it out:

session.query(ActionType).filter(ActionType.actions.any()).all()

The any() does the trick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.