Django ORM Relationships Cheat Sheet – Hacker Noon

Polymorphic Many to Many Relationship

With package — django-polymorphic.

Demo details:

In this demo we have 3 models (Valet, Owner and Car), and 4 tables (valets, owners, cars and drivers).

Business Rules:

The Valet (driver) can drive many Cars
The Owner (driver) can drive many Cars.
The Car can be driven by many drivers (Valet or/and Owner).

Relations Diagram:

Relationship Details:

The Pivot table “drivers” should store the Driver ID, Driver Type and the CarID.
“driver” is a name given to a group of models (Valet and Owner). And it’s not limited to two. The driver type is the real name of the model.

Models:

from polymorphic.models import PolymorphicModel
class Driver(PolymorphicModel):
pass

class
Owner(Driver):

# ...
name = models.CharField(max_length=255)

class Valet(Driver):

# ...
name = models.CharField(max_length=255)

class Car(models.Model):

# ...

name = models.CharField(max_length=255)
drivers = models.ManyToManyField(
Driver,
related_name='cars'
)

Store Records:

# Create relation between driver (Valet/Owner) and Car.
owner.cars.add(car1, car2)
# Create relation between Car and driver (Valet/Owner).
car.drivers.add(owner, valet)

Retrieve Records:

# Get driver (Valet/Owner) Cars
valet.cars.all()
owner.cars.all()
# Get Car drivers (Valet and Owner)
car.drivers.all()
car1.drivers.instance_of(Valet)
car1.drivers.instance_of(Owner)

I also highly recommend to read the article, that describes polymorphic many to many relationships with another django package (django-gm2m).

read original article here