I have been trying to make search_fields able to search for fields in another table on the django admin page. I discovered that I could use a function to achieve my goal, but when I went to the admin page, in place of the data I wanted it to display, it would display <django.db.models.query_utils.DeferredAttribute object at 0x00000208375C9280>
Here is my admin.py file:
from django.contrib import admin
from .models import RiskRegister, Category, Severity, RSev
from account.models import Account
class RiskRegisterAdmin(admin.ModelAdmin):
list_display = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity',
'action_taken_explanation', 'created_at']
list_filter = ['id', 'user', 'date', 'category', 'roles', 'responderID', 'severity', 'action_taken_explanation']
search_fields = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity', 'created_at']
def user_dept(self, obj):
return Account.department
And my models.py file containing the Account model:
class Account(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=150, unique=True)
email = models.EmailField(verbose_name='email', max_length=254, unique=True)
department = models.CharField(verbose_name='department', max_length=100, editable=True)
first_name = models.CharField(verbose_name='first name', max_length=254, blank=True)
last_name = models.CharField(verbose_name='last name', max_length=254, blank=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
How can I make it display what is in the department?
CodePudding user response:
The obj
is the model object here, you can this present this with obj.user.department
:
class RiskRegisterAdmin(admin.ModelAdmin):
list_display = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity',
'action_taken_explanation', 'created_at']
list_filter = ['id', 'user', 'date', 'category', 'roles', 'responderID', 'severity', 'action_taken_explanation']
search_fields = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity', 'created_at']
def user_dept(self, obj):
return obj.user.department
You can boost efficiency with a .select_related(…)
clause [Django-doc]:
class RiskRegisterAdmin(admin.ModelAdmin):
# ⋮
def get_queryset(self, request):
qs = super().get_queryset(request).select_related('user')