简体   繁体   English

如何使用 SQLAlchemy 将默认/预先存在的行作为准备使用的对象?

[英]How to have default/pre-existing rows as ready to use objects using SQLAlchemy?

I'm developing a system using SQLALchemy to persist my data.我正在开发一个使用 SQLALchemy 来保存数据的系统。 I'd like to have objects of my default rows so I could use then when creating new instances.我想拥有我的默认行的对象,以便在创建新实例时可以使用。

This would be very good for me since some tables are supposed to have some default values.这对我来说非常好,因为有些表应该有一些默认值。 Imagine a simple relation between trow tables (order and order_status).想象一下 trow 表(order 和 order_status)之间的简单关系。 When inserting values in order, it would be nice to have an easy way to use some of this default values already in order_status without having to query for them every time.按顺序插入值时,最好有一种简单的方法来使用 order_status 中已有的一些默认值,而不必每次都查询它们。

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker


engine = create_engine('sqlite:///:memory:')

Base = declarative_base()

class Order(Base):
    __tablename__ = 'order'

    id = Column(Integer, primary_key=True)
    order_status_id = Column(Integer, ForeignKey('order_status.id'))
    value = Column(Integer)

    order_status = relationship('OrderStatus', lazy=True, uselist=False)

class OrderStatus(Base):
    __tablename__ = 'order_status'

    id = Column(Integer, primary_key=True)
    name = Column(String(32))

Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

finished = OrderStatus(name='Finished')
session.add(finished)
session.commit()

For example, I'd like to create a new instance of Order using something like:例如,我想使用以下内容创建 Order 的新实例:

order = Order(value=10, order_status=OrderStatus.FINISHED)

Instead of:代替:

finished_status = session.query(OrderStatus).filter_by(name='Finished').first()
order = Order(value=10, order_status=finished_status)

It does not need to be implemented exactly like my example, but I'd like something similar它不需要完全像我的例子一样实现,但我想要类似的东西

You should take a look at the association_proxy : https://docs.sqlalchemy.org/en/13/orm/extensions/associationproxy.html你应该看看association_proxyhttps : //docs.sqlalchemy.org/en/13/orm/extensions/associationproxy.html

The example pretty much fits your question.该示例非常适合您的问题。 Your Order could finally look somewhat like this (obviously not copy&paste'able):您的Order最终可能看起来像这样(显然不能复制和粘贴):

class OrderStatus(Base):
    ...

class Order(Base):
    __tablename__ = 'order'

    id = Column(Integer, primary_key=True)
    order_status_id = Column(Integer, ForeignKey('order_status.id'))
    value = Column(Integer)

    _order_status = relationship('OrderStatus', lazy=True, uselist=False)
    order_status = association_proxy('_order_status', 'name', creator=get_or_create_order_status)

def get_or_create_order_status(name):
    # get or create a order status by name

In get_or_create_order_status you probably have to go back to querying (at least initially to eg fill a cache).get_or_create_order_status您可能必须返回查询(至少最初是为了例如填充缓存)。

If the OrderStatus is actually as simple as in your question, maybe an enum would do the trick as well.如果OrderStatus实际上和您的问题一样简单,也许enum也可以解决问题。 That would obviously be much easier to manage.这显然会更容易管理。

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

相关问题 如何加载预先存在的数据烧瓶-sqlalchemy - how to load pre-existing data flask-sqlalchemy 如何从 SQlAlchemy ORM 会话查询预先存在的表? - How to query pre-existing table from SQlAlchemy ORM session? 如何使用for循环并通过使用append从预先存在的列表中删除项目? - How to remove an item from a pre-existing list using a for loop and through the use of append? 根据预先存在的行连接数据帧 - concatenating dataframes based on pre-existing rows SQLAlchemy的; 将主键设置为预先存在的db表(不使用sqlite) - Sqlalchemy; setting a primary key to a pre-existing db table (not using sqlite) 如何在sqlalchemy中更改现有数据库表的两个不同的列标题? - How do I alter two different column headers of a pre-existing database table in sqlalchemy? 如何重新输入预先存在的 django 应用程序 - How to reenter a pre-existing django app 如何在预先存在的浏览器中运行 Selenium? - How to run Selenium in pre-existing browser? 在 Windows 7 中与 USB 设备通信并仍然使用预先存在的驱动程序? - Communicating to USB devices in windows 7 and still use pre-existing drivers? 如何使用python向csv文件中的预先存在的行添加一个值 - How to add a add a value to a pre-existing row in a csv file using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM