简体   繁体   English

通过主键进行SQLAlchemy初始化

[英]SQLAlchemy init by primary key

I'm writing a sqlalchemy based python app. 我正在写一个基于sqlalchemy的python应用程序。 I want to override the sqlalchemy init method which will accept a primary key and then init it's own instance. 我想重写sqlalchemy的init方法,该方法将接受主键,然后将其初始化为自己的实例。

Something like this: 像这样:

class User(Base):
    id = Column(String, primary_key=True)
    name = Column(String)

    def __init__(id):
        self = session.query(User).filter(User.id=id).first()

I know I can initialize the object using session.query, but I want to export a nice simple api that will be used by other users (It's going to be a SDK). 我知道我可以使用session.query初始化对象,但是我想导出一个很好的简单api,供其他用户使用(它将是一个SDK)。

Any ideas? 有任何想法吗? Thanks! 谢谢!

You can do this via the init method, though I would recommend against it. 可以通过init方法执行此操作,尽管我建议不要这样做。

There are two issues with your code snippet. 您的代码段有两个问题。

  1. You forgot to include the self argument as the first argument of the __init__ method 您忘记了将self参数作为__init__方法的第一个参数
  2. Assigning to self would not work, but you can replace the dictionary of self with that of other 分配给self无效,但是您可以将self字典替换为其他字典

putting these two things together: 将这两件事放在一起:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, user_id):
        res = session.query(User).filter(User.id == user_id).first()
        self.__dict__ = res.__dict__

However, I'd recommend adding a classmethod for this very specific but oft-repeated usage, ie getting an instance from the database by the primary_key 但是,我建议针对这种非常特定但经常重复的用法添加类方法,即通过primary_key从数据库获取实例

@classmethod
def get_by_id(cls, key):
    return session.query(cls).filter(cls.id == key).first()

This way it is general to all your classes that have a single column primary key. 这样,对具有单个列主键的所有类都是通用的。

The usage for these versions would be 这些版本的用法是

u1 = User(user_id=1)
u2 = User.get_by_id(key=1)

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

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