[Answered ]-Django models dependencies and transfer ownership

1👍

You can say that Produser, Store and Customer all have something in common, i.e. they can own a HoneyPot. Meaning they are specializations of let’s say an entity that can own a HoneyPot. To model this we would simply add an extra model which Produser, Store and Customer all will either inherit from or have a one to one relationship with.

Using a OneToOneField [Django docs]:

We can simply make the relationship by using a OneToOneField:

class HoneyPotOwner(models.Model):
    PRODUCER = 'P'
    STORE = 'S'
    CONSUMER = 'C'
    TYPE_CHOICES = [
        (PRODUCER, 'Producer'),
        (STORE, 'Store'),
        (CONSUMER, 'Consumer'),
    ]
    owner_type = models.CharField(max_length=1, choices=TYPE_CHOICES)

class Produser(models.Model):
    honey_pot_owner = models.OneToOneField(HoneyPotOwner, on_delete=models.CASCADE)
    ...

class Store(models.Model):
    honey_pot_owner = models.OneToOneField(HoneyPotOwner, on_delete=models.CASCADE)
    ...

class Customer(models.Model):
    honey_pot_owner = models.OneToOneField(HoneyPotOwner, on_delete=models.CASCADE)
    ...

class HoneyPot(models.Model):
    produced_date = models.DateField(auto_now=False)
    pot_id = models.CharField(max_length=25, blank=False)
    owner = models.ForeignKey(HoneyPotOwner, on_delete=models.CASCADE)

Using Multi-table inheritance:

We can have Produser, Store and Customer inherit from HoneyPotOwner this is called Multi-table inheritance. This implicitly makes the OneToOneField, but has a few advantage that accessing the related fields becomes a little easier:

class HoneyPotOwner(models.Model):
    PRODUCER = 'P'
    STORE = 'S'
    CONSUMER = 'C'
    TYPE_CHOICES = [
        (PRODUCER, 'Producer'),
        (STORE, 'Store'),
        (CONSUMER, 'Consumer'),
    ]
    owner_type = models.CharField(max_length=1, choices=TYPE_CHOICES)

class Produser(HoneyPotOwner):
    ...

class Store(HoneyPotOwner):
    ...

class Customer(HoneyPotOwner):
    ...

class HoneyPot(models.Model):
    produced_date = models.DateField(auto_now=False)
    pot_id = models.CharField(max_length=25, blank=False)
    owner = models.ForeignKey(HoneyPotOwner, on_delete=models.CASCADE)

Leave a comment