Skip to content

Extend the base SQLAlchemy utility methods in models/utils.py to allow loading relationships in asyncpg #41

@devraj

Description

@devraj

Due to how the 2.0 syntax works and using asyncpg writing generic helper methods when using relationships becomes a lot trickers. Essentially you have to write a select as follows:

        query = select(cls).options(selectinload(cls.memberships),\
            selectinload(cls.card_holder))

for the relationships to work. This makes writing generic CRUD wrapper difficult.

The proposal here is to write a generic method called _get_select which provides the joined configuration of the select statement which other get methods can use to apply conditions to e.g:

        query = select(cls).options(selectinload(cls.memberships),\
            selectinload(cls.card_holder))\
            .where(or_(cls.email == email,\
                cls.mobile_number == mobile_number))

a refactored version would then look like

        query = cls._get_select()
            .where(or_(cls.email == email,\
                cls.mobile_number == mobile_number))

each class inheriting from the ModelCRUDMixin can override that to provide the appropriate configuration, allowing the global getting to work across models and making it easier to write other getters.

Another benefit of this approach will be that as the relationships are modified they can be changed in one spot and all other getters remain unchanged.

See also #38

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions