keyword-based get() for composite primary key
See original GitHub issueMigrated issue, originally created by Alex Rothberg
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
)
)
Issue Analytics
- State:
- Created 5 years ago
- Comments:11 (3 by maintainers)
Top Results From Across the Web
Composite Key in SQL: Your Ultimate Guide to Mastery
The primary key is a constraint that recognizes all of the columns in a row as unique. For a constraint to be recognized...
Read more >Composite Key in SQL
A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify...
Read more >SQL COMPOSITE KEY
Composite key is a key which is the combination of more than one field or column of a given table. It may be...
Read more >Learn How to Use Composite Key in SQL
The Composite Key in SQL is a combination of two or more columns, which are used to identify the rows from a table....
Read more >PostgreSQL Composite Primary Keys
Sometimes you can guarantee uniqueness of a record through a combination of column values. This is what a composite key is. It's a...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@sanjana96 that is the general idea, although it requires a few changes. if you can submit as a PR I can illustrate; the conversion from mapper.primary_key needs to be stated in terms of attribute names, not column keys, and I’d like to see if there’s a way to implement the test for length only once rather than stating it twice (easier to maintain and cover in tests).
Here’s an MCVE that works, try this