I'm working on a project using Django(3) in which I have created a model that has various ForeignKey
fields. Now in the admin, I want to check if these ForeignKey
fields are None or not, How can I do that?
Here's what I have tried:
From models.py
:
class ReportsModel(models.Model):
cdr_report = models.OneToOneField(CurrencyDistributionModel,
on_delete=models.CASCADE, null=True, default=None)
cme_report = models.OneToOneField(CurrencyManagementExpenditureModel,
on_delete=models.CASCADE, null=True, default=None)
cps_report = models.OneToOneField(CurrencyProcessingStorageModel,
on_delete=models.CASCADE, null=True, default=None)
cma_report = models.OneToOneField(CurrencyManagementAssetsModel,
on_delete=models.CASCADE, null=True, default=None)
def __str__(self):
if self.cdr_report is not None:
return self.cdr_report.RequestId
elif self.cme_report is not None:
return self.cme_report.RequestId
elif self.cps_report is not None:
return self.cps_report.RequestId
elif self.cma_report is not None:
return self.cma_report.RequestId
From admin.py
:
class ReportAdmin(ReverseModelAdmin):
report = None
if ReportsModel.cdr_report is not None:
report = 'cdr_report'
elif ReportsModel.cme_report is not None:
report = 'cme_report'
elif ReportsModel.cps_report is not None:
report = 'cps_report'
elif ReportsModel.cma_report is not None:
report = 'cma_report'
search_fields = ['name']
inline_reverse = [report]
# inline_reverse = ['cdr_report', 'cme_report',
# 'cps_report', 'cma_report']
inline_type = 'stacked'
admin.site.register(ReportsModel, ReportAdmin)
But in admin, it didn't work, it only shows the correct value for cdr_report
not for others. I want to display only the report
which is not None
. How can I achieve that?
question from:
https://stackoverflow.com/questions/65888918/django-access-foreignkey-field-data-base-on-a-condition-in-admin 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…