My app contains the following two models:
class Counter(models.Model):
external_id = models.CharField(max_length=255)
service = models.ForeignKey(Service, on_delete=models.CASCADE)
unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
class CounterValue(models.Model):
counter = models.ForeignKey(Counter, on_delete=models.CASCADE)
date = models.DateField()
value = models.DecimalField(max_digits=10, decimal_places=3)
current_baseline = models.BooleanField(default=False)
I need to add another Counter model, and wonder whether I should use an abstract base class –
# new base model
class Counter(models.Model):
external_id = models.CharField(max_length=255)
service = models.ForeignKey(Service, on_delete=models.CASCADE)
class Meta:
abstract=True
class ServiceCounter(Counter):
pass
# former Counter() model
class UnitCounter(Counter):
unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
class CounterValue(models.Model):
counter = models.ForeignKey(Counter, on_delete=models.CASCADE)
date = models.DateField()
value = models.DecimalField(max_digits=10, decimal_places=3)
current_baseline = models.BooleanField(default=False)
– or multi-table inheritance –
# new model
class ServiceCounter(models.Model):
external_id = models.CharField(max_length=255)
service = models.ForeignKey(Service, on_delete=models.CASCADE)
# former Counter() model
class UnitCounter(ServiceCounter):
unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
class Meta:
db_table = 'services_counter'
class CounterValue(models.Model):
counter = models.ForeignKey(ServiceCounter, on_delete=models.CASCADE)
date = models.DateField()
value = models.DecimalField(max_digits=10, decimal_places=3)
current_baseline = models.BooleanField(default=False)
– to be able to filter CounterValue() objects with both ServiceCounter() and UnitCounter() objects.
If the abstract base class approach is recommended: How would I migrate the existing table ‘services_counter’ (which is currently used for the old Counter() model)?