Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - Django Access ForeignKey field data base on a condition in Admin

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...