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:

  1. class Product(db.Entity):
  2. name = Required(str, unique=True)
  3. price = Required(Decimal)
  4. def get_name_and_price(self):
  5. 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:

  1. class ProductMixin(object):
  2. def get_name_and_price(self):
  3. return "%s (%s)" % (self.name, self.price)
  4. class Product(db.Entity, ProductMixin):
  5. name = Required(str, unique=True)
  6. 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:

  1. class ProductMixin(object):
  2. def get_name_and_price(self):
  3. return "%s (%s)" % (self.name, self.price)

File models.py:

  1. from decimal import Decimal
  2. from pony.orm import *
  3. from mixins import *
  4. class Product(db.Entity, ProductMixin):
  5. name = Required(str, unique=True)
  6. price = Required(Decimal)