Display foreign key columns as link to detail object in Django admin

后端 未结 3 742
小鲜肉
小鲜肉 2021-02-02 04:18

As explained in link-in-django-admin-to-foreign-key-object, one can display a ForeignKey field as a link to the admin detail page.

To summarize,

class Fo         


        
3条回答
  •  一个人的身影
    2021-02-02 04:52

    A slight respin on the accepted answer. It is not necessarily better, but implements some of the advice in the comments:

    from django.contrib.contenttypes.models import ContentType
    from django.urls import reverse
    from django.utils.html import format_html
    
    
    def linkify(field_name):
        def _linkify(obj):
            content_type = ContentType.objects.get_for_model(obj)
            app_label = content_type.app_label
            linked_obj = getattr(obj, field_name)
            linked_content_type = ContentType.objects.get_for_model(linked_obj)
            model_name = linked_content_type.model
            view_name = f"admin:{app_label}_{model_name}_change"
            link_url = reverse(view_name, args=[linked_obj.pk])
            return format_html('{}', link_url, linked_obj)
    
        _linkify.short_description = field_name.replace("_", " ").capitalize()
        return _linkify
    

提交回复
热议问题