Django polymorphic relation pointing directly to records in related models

35 Views Asked by At

Im my django application I have following models:

class Customer(models.Model):
    ...

class CustomMetric(models.Model):
    customer = models.ForeignKey(Customer, db_column="id", on_delete=models.CASCADE, related_name='custom_metrics')
    name = models.CharField(max_length=100)
    function = models.TextField()


class StoreData(model.Model):
    ...


class CarData(model.Model):
    ...

If customer adds new custom_metric, it should save this record and based on column function (which is written in string formula for example cost * 5), calculate it for each record in StoreData and CarData models and somehow save this value to database(I can't calculate it on run, because these functions are very complex).

I was thinking about adding new model called CustomMetricsValues and use django-polymorphic. Something like that:

class CustomMetricsValue(model.Model):
   custom_metric = models.ForeignKey(CustomMetric, db_column="id", on_delete=models.CASCADE, related_name='custom_metric_values')
   value = models.FloatField() # here I would save calculated value
   related_field = FK # here somehow I should store information about for which table and which record is that (for example table StoreData record id 2)

But I failed because it only saved information regarding which table this record is related(for example StoreData but, it doesn't tell for wchich record from this table this custom value belongs. Am I doing something wrong? Or is there any better solution?

I don't want to add new table per every related model because in future I will be adding more of them. Also cannot merge CarData and StoreData into one table.

0

There are 0 best solutions below