4

假设我在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不是“真实”属性。有没有办法做这种事情,允许计算字段被视为可以对其进行正常聚合/计算的一流实体?

4

1 回答 1

3

感谢您的建议!

目前(2015 年 2 月)Pony ORM 不支持计算字段,但是这个功能可以相对容易地实现,因为 Pony 已经具备将 lambdas 转换为 SQL的能力。我希望我们能尽快添加计算字段。

于 2015-02-18T18:13:58.767 回答