我使用sqlalchemy與金字塔框架,並且我想使用他的郵政編碼將一個人鏈接到他的地理部門。 所以我嘗試在定義department_id列時定義department_id時使用onupdate參數。 看到休耕代碼:基於sqlalchemy聲明基礎的另一個字段onupdate
from datetime import date
from emailing.models import Base, DBSession
from sqlalchemy import Column, Integer, Unicode, Text, DateTime, Sequence, Boolean, Date, UnicodeText, UniqueConstraint, Table, ForeignKey
from sqlalchemy.orm import scoped_session, sessionmaker, column_property, relationship, backref
from sqlalchemy.sql import func
class Person(Base):
__tablename__ = u'person'
id = Column(Integer, primary_key=True)
firstName = Column(Unicode(255))
lastName = Column(Unicode(255))
created_at = Column(Date, default=func.now())
updated_at = Column(Date, onupdate=func.now())
department_id = Column(Integer(), ForeignKey('department.id'), onupdate=dep_id_from_postcode)
department = relationship("Department", backref='persons')
__table_args__ = (UniqueConstraint('firstName', 'lastName'), {})
def dep_id_from_postcode(self):
return int(self.postcode[:2])
上更新了的updated_at領域工作正常,但對於deparment_id領域它告訴我:
NameError: name 'dep_id_from_postcode' is not defined
我已經找到關於Python的文檔在此執行功能:http://docs.sqlalchemy.org/en/latest/core/schema.html?highlight=trigger#python-executed-functions 但沒有使用其他字段在onupdate參數中使用的內容。
我希望我清楚到足夠多的,因爲我不是一個「自然英語的人」 謝謝大家
也謝謝你,它正是我正在做什麼後readeing範的回答。東西是context.current_parameters似乎是隨機填充的(有時它包含一個關鍵的郵政編碼,有時不是)(它似乎並不連接,無論我在哪裏或不更新郵編字段)(也許因爲我是一個20其他的東西該類別中的夥伴) – Yohann
僅供參考,更新的鏈接:http://docs.sqlalchemy.org/en/rel_0_9/core/defaults。html#context-sensitive-default-functions –
當你調用'.update'來更新一些值並且它們不包含''postcode''時,這將不起作用。 – fiatjaf