Hybrid methods and properties

(new in version 0.7.4)

You can declare methods and properties inside your entity that you can use in queries. Important that hybrids and properties should contain single line return statement.

  1. class Person(db.Entity):
  2. first_name = Required(str)
  3. last_name = Required(str)
  4. cars = Set(lambda: Car)
  5. @property
  6. def full_name(self):
  7. return self.first_name + ' ' + self.last_name
  8. @property
  9. def has_car(self):
  10. return not self.cars.is_empty()
  11. def cars_by_color(self, color):
  12. return select(car for car in self.cars if car.color == color)
  13. # or return self.cars.select(lambda car: car.color == color)
  14. @property
  15. def cars_price(self):
  16. return sum(c.price for c in self.cars)
  17. class Car(db.Entity):
  18. brand = Required(str)
  19. model = Required(str)
  20. owner = Optional(Person)
  21. year = Required(int)
  22. price = Required(int)
  23. color = Required(str)
  24. with db_session:
  25. # persons' full name
  26. select(p.full_name for p in Person)
  27. # persons who have a car
  28. select(p for p in Person if p.has_car)
  29. # persons who have yellow cars
  30. select(p for p in Person if count(p.cars_by_color('yellow')) > 1)
  31. # sum of all cars that have owners
  32. sum(p.cars_price for p in Person)