Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python, django, display the correct field name by FK, linked tables

models.py file

#create class roles, id, portal_name, role_name
class Roles(models.Model):
    portal_name = models.CharField(_('Portal name'), max_length=100)
    role_name = models.CharField(_('Role_name'), max_length=50)


#create permission for roles
class RolePermission(models.Model):
    module_name = models.CharField(_('Module name'), max_length=100)
    module_delete = models.BooleanField(default=False, help_text="Delete module. Default false, can't delete")
    module_edit = models.BooleanField(default=False, help_text="Edit module. Default false, can't edit")
    module_create = models.BooleanField(default=False, help_text="Create module. Default false, can't create")
    module_submit = models.BooleanField(default=False, help_text="Submit module, Default false.")
    module_role_id = models.ForeignKey('Roles', on_delete=models.CASCADE)

enter image description here

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my admin.py file

@admin.register(RolePermission)
class RolePermissionAdmin(admin.ModelAdmin):
    list_display = ('module_name', 'module_role_id_id', 'module_delete', 'module_edit', 'module_create', 'module_submit')

as in the column display information on role_name from table roles, used Foreign Key

>Solution :

You can define a method, and use the name of that method in the list_display. For this specific case we thus the role_name of the related .module_role_id:

@admin.register(RolePermission)
class RolePermissionAdmin(admin.ModelAdmin):
    list_display = ('module_name', 'role_name', 'module_delete', 'module_edit', 'module_create', 'module_submit')

    @admin.display(description='role name')
    def role_name(self, obj):
        return obj.module_role_id.role_name

Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be module_role, instead of module_role_id.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading