keyword-based get() for composite primary key

Issue #4316 new
Alex Rothberg
created an issue

Right now the ident parameter to query.get is a tuple in the case of composite primary keys with the stipulation:

For a composite primary key, the order of identifiers corresponds in most cases to that of the mapped :class:.Table object's primary key columns.

Having to know and hard code the order of the primary keys seems less than ideal. I suggest accepting a dict mapping names to the values for the primary keys. My implementation of this looks like:

from sqlalchemy.inspection import inspect

def get_by_pks(model, **kwargs):
    return model.query.get(
        tuple(
            kwargs[key.name]
            for key in inspect(model).primary_key
        )
    )

Comments (3)

  1. Michael Bayer repo owner

    Well the concept of "pk" is dealt with a lot in util.identity_key() and there is also the concept of an "identity_token" that can further distinguish objects of the same primary key in one session. So a get_by_key() as:

    get_by_key(dict(x=1, y=2))
    
    get_by_key(dict(x=1, y=2), identity_token='foo')
    

    we can work through a PR for this any time you or someone wants to propose.

  2. Log in to comment