1
我使用的SQLAlchemy的單表繼承了Transaction
,StudentTransaction
和CompanyTransaction
SQLAlchemy的關係:與單表繼承
class Transaction(Base):
__tablename__ = 'transaction'
id = Column(Integer, primary_key=True)
# Who paid? This depends on whether the Transaction is a
# CompanyTransaction or a StudentTransaction. We use
# SQLAlchemy's Single Table Inheritance to make this work.
discriminator = Column('origin', String(50))
__mapper_args__ = {'polymorphic_on': discriminator}
# When?
time = Column(DateTime, default=datetime.utcnow)
# Who administered it?
staff_id = Column(Integer, ForeignKey('staff.id'))
staff = relationship(
'Staff',
primaryjoin='and_(Transaction.staff_id==Staff.id)'
)
# How much?
amount = Column(Integer) # Negative for refunds, includes the decimal part
# Type of transaction
type = Column(Enum(
'cash',
'card',
'transfer'
))
class CompanyTransaction(Transaction):
__mapper_args__ = {'polymorphic_identity': 'company'}
company_id = Column(Integer, ForeignKey('company.id'))
company = relationship(
'Company',
primaryjoin='and_(CompanyTransaction.company_id==Company.id)'
)
class StudentTransaction(Transaction):
__mapper_args__ = {'polymorphic_identity': 'student'}
student_id = Column(Integer, ForeignKey('student.id'))
student = relationship(
'Student',
primaryjoin='and_(StudentTransaction.student_id==Student.id)'
)
然後,我有一個學生,它定義與StudentTransactions一個一對多的關係:
class Student(Base):
__tablename__ = 'student'
id = Column(Integer, primary_key=True)
transactions = relationship(
'StudentTransaction',
primaryjoin='and_(Student.id==StudentTransaction.student_id)',
back_populates='student'
)
@hybrid_property
def balance(self):
return sum([transaction.amount for transaction in self.transactions])
問題是,調用Student yield:NotImplementedError: <built-in function getitem>
爲Student.balance()
函數的返回行。
我在做什麼錯?
謝謝。
謝謝,這有效 - 很好的答案! – sssilver
只有一個問題:什麼時候「平衡」在實例級調用,什麼時候在類級調用?當我在實例級別的'balance'上放置一個斷點時,我仍然可以看到它正在被調用。 – sssilver
課程級別是:Student.balance,實例級別是:s = Student(); s.balance。我可以在實例級別balance()中放置「引發Exception()」,運行腳本,但不會調用它。 – zzzeek