简体   繁体   中英

Django - Foreign Keys and the Admin Page

I am trying to display the foreign key relations on the admin change page (ie the www.some.url/admin/<app>/<model>/<id>/change/ page):

I have two models linked together via a foreign key relationship like so:

# models.py

class Bank(models.Model):
    name = models.CharField(max_length=100)

class Branch(models.Model):
    bank = models.ForeignKey('Bank', on_delete=models.CASCADE, related_name='branches')
    name = models.CharField(max_length=100)

And I have a model-admin like so:

# admin.py

class BankAdmin(admin.ModelAdmin):

    list_display = ('id', 'name',)

How can I add the list of branches associated to a given bank on the django-admin-change page? Can I add something to my BankAdmin class that will achieve this?

ie If I were to visit the admin page and click on a bank instance (ie www.some.url/admin/<app>/bank/2/change/ ) I would like to see the name of the bank and all of its foreign-key related branches.

I've been scouring stackoverflow but have found a solution - please point me in the correct direction if one does exist.

One solution would be to register a link in BankAdmin's list display that points to a custom admin view showing that Bank's Branches. You could do so like this:

# admin.py

class BankAdmin(admin.ModelAdmin):

    def link_branches(self, obj):
        return format_html(
            "<a href='/admin/<app>/bank/branches/?id={ bank_id }'> Branches </a>",
            bank_id=obj.id
        )

    list_display = ('id', 'name', 'link_branches')
    admin.site.register(Bank, BankAdmin)

Then you just have to create your custom view and update your urls.py to point /admin/<app>/bank/branches to that view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM