SQLAlchemy声明式中基于对象的默认值

SQLAlchemy声明式中基于对象的默认值

本文介绍了SQLAlchemy声明式中基于对象的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SQLAlchemy,可以向每个函数添加默认值.据我了解,这也可能是可调用的(没有任何参数或带有可选的ExecutionContext参数).

With SQLAlchemy, it is possible to add a default value to every function. As I understand it, this may also be a callable (either without any arguments or with an optional ExecutionContext argument).

现在在声明性场景中,我想知道是否可以通过某种方式使用存储的 object 调用默认函数. IE.可能像这样:

Now in a declarative scenario, I wonder if it is somehow possible to have a default function which is called with the object that is being stored. I.e. possibly like so:

Base = sqlalchemy.ext.declarative.declarative_base()
class BaseEntity(Base):
    value = Column('value', String(40), default=BaseEntity.gen_default)

    def gen_default(self):
        # do something with self, for example
        # generate a default value using some other data
        # attached to the object
        return self.default_value

像这样可能吗?还是我必须为此设置一个插入前钩子(如何?)?

Is something like this possible? Or do I have to somehow set up an before-insertion hook for this (how?)?

推荐答案

在此插入文档

http://docs. sqlalchemy.org/en/rel_0_7/orm/events.html#sqlalchemy.orm.events.MapperEvents.before_insert

此处的示例:

http://docs.sqlalchemy.org/en/rel_0_7/orm/events.html#mapper-events

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event

Base= declarative_base()

class A(Base):
    __tablename__ = "a"


    id = Column(Integer, primary_key=True)
    data = Column(String)
    otherdata = Column(String)

@event.listens_for(A, "before_insert")
def gen_default(mapper, connection, instance):
    instance.data = "Some default %s" % instance.otherdata

e = create_engine("sqlite://")
Base.metadata.create_all(e)

a = A(otherdata="some other data")
s = Session(e)
s.add(a)
s.commit()

assert a.data == "Some default some other data"

这篇关于SQLAlchemy声明式中基于对象的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:18