Skip to content

Latest commit

 

History

History
113 lines (86 loc) · 4.27 KB

File metadata and controls

113 lines (86 loc) · 4.27 KB

title: sqlalchemy.orm Load Example Code category: page slug: sqlalchemy-orm-load-examples sortorder: 500031056 toc: False sidebartitle: sqlalchemy.orm Load meta: Example code for understanding how to use the Load class from the sqlalchemy.orm module of the SQLAlchemy project.

Load is a class within the sqlalchemy.orm module of the SQLAlchemy project.

ColumnProperty, CompositeProperty, Mapper, Query, RelationshipProperty, Session, SynonymProperty, aliased, attributes, backref, class_mapper, column_property, composite, interfaces, mapper, mapperlib, object_mapper, object_session, query, relationship, session, sessionmaker, and strategies are several other callables with code examples from the same sqlalchemy.orm package.

Example 1 from SQLAlchemy filters

SQLAlchemy filters provides filtering, sorting and pagination for SQLAlchemy query objects, which is particularly useful when building web APIs. SQLAlchemy filters is open sourced under the Apache License version 2.0.

SQLAlchemy filters / sqlalchemy_filters / loads.py

# loads.py
~~from sqlalchemy.orm import Load

from .exceptions import BadLoadFormat
from .models import Field, auto_join, get_model_from_spec, get_default_model


class LoadOnly(object):

    def __init__(self, load_spec):
        self.load_spec = load_spec

        try:
            field_names = load_spec['fields']
        except KeyError:
            raise BadLoadFormat('`fields` is a mandatory attribute.')
        except TypeError:
            raise BadLoadFormat(
                'Load spec `{}` should be a dictionary.'.format(load_spec)
            )

        self.field_names = field_names

    def get_named_models(self):
        if "model" in self.load_spec:
            return {self.load_spec['model']}
        return set()

    def format_for_sqlalchemy(self, query, default_model):
        load_spec = self.load_spec
        field_names = self.field_names

        model = get_model_from_spec(load_spec, query, default_model)
        fields = [Field(model, field_name) for field_name in field_names]

~~        return Load(model).load_only(
            *[field.get_sqlalchemy_field() for field in fields]
        )


def get_named_models(loads):
    models = set()
    for load in loads:
        models.update(load.get_named_models())
    return models


def apply_loads(query, load_spec):
    if (
        isinstance(load_spec, list) and
        all(map(lambda item: isinstance(item, str), load_spec))
    ):
        load_spec = {'fields': load_spec}

    if isinstance(load_spec, dict):
        load_spec = [load_spec]

    loads = [LoadOnly(item) for item in load_spec]

    default_model = get_default_model(query)


## ... source file continues with no further Load examples...