Look into how normalization works, since all models have 2 common fields lets say you have a table called Report and it has the fields RequestId
and InstCode
. Now all your other models can be said to be in a XYZReport is a Report
kind of relationship.
You can achieve this using a OneToOne Field like so:
class Report(models.Model):
RequestId = models.CharField(max_length=256, blank=False, default=0)
InstCode = models.CharField(max_length=3, blank=False)
DISTRIBUTION = 'DI'
EXPENDITURE = 'EX'
STORAGE = 'ST'
ASSETS = 'AS'
REPORT_TYPE_CHOICES = [
(DISTRIBUTION, 'Distribution Report'),
(EXPENDITURE, 'Expenditure Report'),
(STORAGE, 'Storage Report'),
(ASSETS, 'Assets Report'),
]
report_type = models.CharField(
max_length=2,
choices=REPORT_TYPE_CHOICES,
default=DISTRIBUTION,
)
# Any more common fields
class DistributionReport(models.Model):
report = models.OneToOneField(
Report,
on_delete=models.CASCADE,
related_name = 'distribution_report'
)
# Other fields
# Other Report models in similar fashion
Now whenever making an object of any kind of report also make an object of Report
and assign it to report attribute of the models. Save both the models, also to figure out what kind of report an instance of Report is add the relevant report_type to the report instance like so:
report.report_type = Report.DISTRIBUTION # In case of Distribution Report
To figure out whether an instance of Report is of a particular type:
report.report_type == report.DISTRIBUTION # will get whether Report is a DistributionReport
To get the specific types object use the related_name set in the OneToOne Field:
distribution_report = report.distribution_report
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…