假设我在Pony ORM中有以下架构:
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
不是真实的"属性。有没有办法做这种事情,允许计算字段被视为可以对它们进行正常聚合/计算的第一类实体?
答案 0 :(得分:3)
感谢您的建议!
目前(2015年2月)Pony ORM不支持计算字段,但此功能可以相对容易地实现,因为Pony已具备translate lambdas to SQL的能力。我希望我们能尽快添加计算字段。