Reputation: 427
Suppose I have the following schema in 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)
I would like the Person
entity to have a salary
attribute that's equal to:
Job.base_salary + (Person.experience * Job.multiplier)
My first thought was to add a property to the Person entity like so:
@property
def salary(self):
return self.job.base_salary + (self.experience * self.job.multiplier)
This works for a simple query:
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
Prints:
Alice 2 90000
Bob 4 100000
Carol 6 110000
Dave 2 44000
Erin 4 48000
Frank 2 32000
Gwen 4 34000
But if I try something like this:
for j in select((j.job_name, avg(j.people.salary)) for j in Job):
print j
Perhaps unsurprisingly, I get:
AttributeError: j.people.salary
since salary
isn't a "real" attribute. Is there a way to do this kind of thing that would allow calculated fields to be treated as first-class entities that can have normal aggregation / calculations done on them?
Upvotes: 4
Views: 425
Reputation: 4849
Thanks for the suggestion!
Currently (Feb 2015) Pony ORM does not support calculated fields, but this feature can be implemented relatively easily, because Pony already have the ability to translate lambdas to SQL. I hope we can add calculated fields soon.
Upvotes: 3