Adding custom methods to entities
Besides data attributes, entities can have methods. The most straightforward way of adding methods to entities is defining those methods in the entity class. Let’s say we would like to have a method of the Product entity which returns concatenated name and price. It can be done the following way:
class Product(db.Entity):
name = Required(str, unique=True)
price = Required(Decimal)
def get_name_and_price(self):
return "%s (%s)" % (self.name, self.price)
Another approach is using mixin classes. Instead of putting custom methods directly to the entity definition, you can define them in a separate mixin class and inherit entity class from that mixin:
class ProductMixin(object):
def get_name_and_price(self):
return "%s (%s)" % (self.name, self.price)
class Product(db.Entity, ProductMixin):
name = Required(str, unique=True)
price = Required(Decimal)
This approach can be beneficial if you are using our online ER diagram editor. The editor automatically generates entity definitions in accordance with the diagram. In this case, if you add some custom methods to the entity definition, these methods will be overwritten once you change your diagram and save newly generated entity definitions. Using mixins would allow you to separate entity definitions and mixin classes with methods into two different files. This way you can overwrite your entity definitions without losing your custom methods.
For our example above the separation can be done in the following way.
File mixins.py:
class ProductMixin(object):
def get_name_and_price(self):
return "%s (%s)" % (self.name, self.price)
File models.py:
from decimal import Decimal
from pony.orm import *
from mixins import *
class Product(db.Entity, ProductMixin):
name = Required(str, unique=True)
price = Required(Decimal)