Generic way to get primary key from declaratively defined instance in SQLAlchemy

2024/10/4 11:19:26

Does SQLAlchemy offer a generic way to get the primary key from a declaratively defined instance, so that if:

Base = declarative_base()class MyClass(Base):__tablename__ = 'mytable'key = Column(Integer, primary_key=True)

I can do:

>>> a = MyClass(key=1)
>>> a.generic_get_primary_key()  # <-- does it exist ??
1
Answer

You can use inspection for that purpose:

http://docs.sqlalchemy.org/en/latest/core/inspection.html

Passing an instance of a mapped object to inspect, returns an InstanceState, describing that object. This state also contains the identity:

Base = declarative_base()class MyClass(Base):__tablename__ = 'mytable'key = Column(Integer, primary_key=True)
a = MyClass(key=1)from sqlalchemy.inspection import inspect    
pk = inspect(a).identity
print pk

Will give:

(1,)

Since primary keys can consist of multiple columns, the identity in general is a tuple containing all the column values that are part of the primary key. In your case, that's simply the key.

https://en.xdnf.cn/q/70617.html

Related Q&A

Add column after another column

How can I add a column after another column to a database using Alembic or SQLAlchemy? That would be equivalent to this SQL clause: ALTER TABLE foo CHANGE COLUMN bar bar COLUMN_DEFINITION_HERE AFTER …

Scrapy Images Downloading

My spider runs without displaying any errors but the images are not stored in the folder here are my scrapy files:Spider.py:import scrapy import re import os import urlparse from scrapy.spiders import …

A full and minimal example for a class (not method) with Python C Extension?

Everywhere, I can easily find an example about writing a method with Python C Extensions and use it in Python. Like this one: Python 3 extension example$ python3 >>> import hello >>> …

Python: Grouping into timeslots (minutes) for days of data

I have a list of events that occur at mS accurate intervals, that spans a few days. I want to cluster all the events that occur in a per-n-minutes slot (can be twenty events, can be no events). I have …

signal.alarm not triggering exception on time

Ive slightly modified the signal example from the official docs (bottom of page).Im calling sleep 10 but I would like an alarm to be raised after 1 second. When I run the following snippet it takes way…

Execute Python (selenium) script in crontab

I have read most of the python/cron here in stackoverflow and yet couldnt make my script run. I understood that I need to run my script through shell (using zsh & ipython by the way), but really I …

Get post data from ajax post request in python file

Im trying to post some data with an ajax post request and execute a python file, retrieving the data in the python file, and return a result.I have the following ajax code$(function () {$("#upload…

How to implement maclaurin series in keras?

I am trying to implement expandable CNN by using maclaurin series. The basic idea is the first input node can be decomposed into multiple nodes with different orders and coefficients. Decomposing singl…

Rowwise min() and max() fails for column with NaNs

I am trying to take the rowwise max (and min) of two columns containing datesfrom datetime import date import pandas as pd import numpy as np df = pd.DataFrame({date_a : [date(2015, 1, 1), date(2012…

Convert column suffixes from pandas join into a MultiIndex

I have two pandas DataFrames with (not necessarily) identical index and column names. >>> df_L = pd.DataFrame({X: [1, 3], Y: [5, 7]})>>> df_R = pd.DataFrame({X: [2, 4], Y: [6, 8]})I c…