In my project I had 2 different set of models for 2 different reports.
TestsReport <-- TestRuns
MetricsReport <-- Metrics --> Values
Then I had to create common Report model to unify and speed up some queries.
First I used just standard explicit ForeignKey relations from TestsReport and MetricsReport to Report and it works fine, but it leads to 3 different set of IDs while just single report ID would be enough.
Also, this way I have to redo access to common fields - say write testReport.report.timestamp instead of testReport.timestamp.
I tried to use Multi-table Inheritance to overcome these drawbacks, but failed to connect TestRuns to TestsReport and Metrics to MetricsReport just using ID these tables inherited from common Report model.
# excerpt from models.py
class HashField(models.DecimalField):
def __init__(self, *args, **kwargs):
super().__init__(*args, **dict(kwargs, max_digits=39, decimal_places=0))
class Report(models.Model):
id = HashField(primary_key=True, unique=True)
timestamp = models.DateTimeField()
# some other fields
class TestsReport(Report):
# some fields
class MetricsReport(Report):
# some fields
This no longer works:
class TestRuns(models.Model):
tests_report = models.ForeignKey('TestsReport', on_delete=models.CASCADE)
# some other fields
Django still creates tests_report_id field in TestRuns table, but it is not connected via foreign key to TestReport’s report_ptr_id field Django created as a result of inheritance.
What has to be done to make Multi-table inheritance work with relationships from other models?