假设我在Pony ORM中有以下模式:
我希望
我的第一个想法是像这样为Person实体添加一个属性:
也许并不令人意外,我得到:
from pony.orm import *
db = Database("postgres", database='foo')
class Job(db.Entity):
job_id = PrimaryKey(int, auto=True)
job_name = Required(str)
base_salary = Required(int)
multiplier = Required(int, default=1000)
people = Set(lambda: Person)
class Person(db.Entity):
person_id = PrimaryKey(int, auto=True)
name = Required(str)
job = Required(lambda: Job)
experience = Required(int)
我希望
Person
实体拥有一个等于以下值的salary
属性:Job.base_salary + (Person.experience * Job.multiplier)
我的第一个想法是像这样为Person实体添加一个属性:
@property
def salary(self):
return self.job.base_salary + (self.experience * self.job.multiplier)
这适用于简单的查询:
j1 = Job(job_name = "Astronaut", base_salary = 80000, multiplier = 5000)
j2 = Job(job_name = "Butcher", base_salary = 40000, multiplier = 2000)
j3 = Job(job_name = "Chef", base_salary = 30000)
for i, name in enumerate(["Alice", "Bob", "Carol"]):
p = Person(name = name, job=j1, experience = i)
for i, name in enumerate(["Dave", "Erin"]):
p = Person(name = name, job=j2, experience = i)
for i, name in enumerate(["Frank", "Gwen"]):
p = Person(name = name, job=j3, experience = i)
for p in select(p for p in Person):
print p.name, p.experience, p.salary
输出:
Alice 2 90000
Bob 4 100000
Carol 6 110000
Dave 2 44000
Erin 4 48000
Frank 2 32000
Gwen 4 34000
但如果我尝试这样做:
for j in select((j.job_name, avg(j.people.salary)) for j in Job):
print j
也许并不令人意外,我得到:
AttributeError: j.people.salary
由于 salary
不是一个“真正的”属性,是否有一种方法可以使计算字段被视为一等实体,可以对其进行正常的聚合/计算处理?