Entity Relationships

Entities can relate to each other. A relationship between two entities is defined by using two attributes which specify both ends of a relationship:

  1. class Customer(db.Entity):
  2. orders = Set('Order')
  3. class Order(db.Entity):
  4. customer = Required(Customer)

In the example above we have two relationship attributes: orders and customer. When we define the entity Customer, the entity Order is not defined yet. That is why we have to put quotes around Order in the orders attribute. Another option is to use lambda:

  1. class Customer(db.Entity):
  2. orders = Set(lambda: Order)

This can be useful if you want your IDE to check the names of declared entities and highlight typos.

Some mappers (e.g. Django) require defining relationships on one side only. Pony requires defining relationships on both sides explicitly (as The Zen of Python reads: Explicit is better than implicit), which allows the user to see all relationships from the perspective of each entity.

All relationships are bidirectional. If you update one side of a relationship, the other side will be updated automatically. For example, if we create an instance of Order entity, the customer’s set of orders will be updated to include this new order.

There are three types of relationships: one-to-one, one-to-many and many-to-many. A one-to-one relationship is rarely used, most relations between entities are one-to-many and many-to-many. If two entities have one-to-one relationship it often means that they can be combined into a single entity. If your data diagram has a lot of one-to-one relationships, then it may signal that you need to reconsider entity definitions.