[Fixed]-Listing Related Fields in Django ModelAdmin

32👍

As per Roseman’s suggestion above, you can display related (one-to-one or many-to-one) data in a readonly manner with Inline admin models. Here’s a little example, just to make sure that we are all on the same page. You can see below that there are three ways to achieve your goal (if I understand that goal correctly).

models.py:

class Company(models.Model):
    name = models.CharField(max_length=50)

class Employee(models.Model):
    name = models.CharField(max_length=50)
    company = models.ForeignKey('Company')
    car = models.ForeignKey('Car')

    def model_callable(self):
        return self.car.rego

class Car(models.Model):
    rego = models.CharField(max_length=50)

admin.py:

def unbound_callable(emp):
    return emp.car.rego

class EmployeeInline(admin.TabularInline):
    model = Employee
    fields = ('name', 'model_callable', 'model_admin_callable', unbound_callable)
    readonly_fields = ('model_callable', 'model_admin_callable', unbound_callable)

    def model_admin_callable(self, emp):
        return emp.car.rego

class CompanyAdmin(admin.ModelAdmin):
    model = Company
    inlines = (EmployeeInline,)

admin.site.register(Company, CompanyAdmin)

As you can see, ‘readonly_fields’ is treated in the same manner as ‘list_display’ as per the Django documentation for contrib.admin (from 1.2 onwards).

In the above example, when you are editing a Company, you will see its employees inlined. Each row will have an employee name in an editable textbox and next to the name you will see a readonly bit of text for the employee’s car’s rego (emp.car.rego).

Referring to your original question, you wanted to reference the related data as ‘other__name’. This won’t work. Expressions like other__name or car__rego only have special meaning as keyword arguments in filters when running Django queries. For example, when fetching an employee who has a car with a particular rego number:

Employee.objects.filter(car__rego='111')

Hope that helps.

j

👤jsw

2👍

Check this Example, it might clear your doubt to render related fields on admin site.

from django.contrib import admin
from . import models


@admin.register(models.Profile)  #Decorator
class ProfileAdmin(admin.ModelAdmin):
    list_display = ['first_name', 'last_name', 'membership', 'phone', 'birth_date']  # Columns to display
    list_select_related = ['user']  # To avoid extra queries

    def first_name(self, profile):
        return profile.user.first_name  # Foreign key relationship
    
    def last_name(self, profile):
        return profile.user.last_name  # Foreign key relationship

In this example I am rendering Profile Model, In which user is Foreign Key to User Model, and User model contains first_name, last_name.

Leave a comment