简体   繁体   English

从 SQLAlchemy 中声明性定义的实例获取主键的通用方法

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

Does SQLAlchemy offer a generic way to get the primary key from a declaratively defined instance, so that if: SQLAlchemy 是否提供了一种从声明式定义的实例中获取主键的通用方法,以便:

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

You can use inspection for that purpose: 您可以为此目的使用inspection

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

Passing an instance of a mapped object to inspect, returns an InstanceState , describing that object. 传递映射对象的实例以进行检查,返回描述该对象的InstanceState 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 . 在你的情况下,这只是key

If you need to retrieve a list primary keys of a class not an instance the following describes how to do it. 如果你需要检索的列表主键class不是一个instance ,下面介绍如何做到这一点。

You can use the inspect method. 您可以使用inspect方法。 This will return an Inspect instance on which you can do your analysis as follows. 这将返回一个Inspect实例,您可以在其上进行如下分析。 In this example I use the Inspect instance to return to me all attribute names of each primary_key of MyClass . 在这个例子中,我使用Inspect实例向我返回MyClass的每个primary_key的所有attribute名称。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class MyClass(Base):
    __tablename__ = "myclass"

    key = Column(Integer, primary_key=True)
    name = Column(String, primary_key=True)



from sqlalchemy import inspect
ins = inspect(MyClass)
print("Tuple of primary keys: ", ins.primary_key)

# Let's loop over them and print the attribute key name of each
for x in ins.primary_key:
    print(x.key)

Returns 返回

> Tuple of primary keys:  (Column('key', Integer(), table=<myclass>, primary_key=True, nullable=False), Column('name', String(), table=<myclass>, primary_key=True, nullable=False))
> key
> name

I did it by getting the primary key name and next, with getattr, passing the class instance and the name of primary key like this: enter image description here我通过获取主键名称来完成它,然后使用 getattr 传递类实例和主键名称,如下所示:在此处输入图像描述

from sqlalchemy.inspection import inspect

# I use this class for all my tables in sqlalchemy
class BaseTablesClass():
    # First I get the name of the primary key, just the first value of array because 
    # a table can have more than a primary key

    def primary_key_name(self):
        return inspect(self).primary_key[0].name

    # Next in this line I get the value of primary key by the name that I get with the
    # method of primary key name
    def primary_key_value(self):
        return getattr(self, self.primary_key_name())

Use inspect function:使用检查功能:

inspect(obj).identity

This will work include "transient" and "pending":这将包括“transient”和“pending”:

inspect(obj.__class__).primary_key_from_instance(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM