Can list_display in a Django ModelAdmin display attributes of ForeignKey fields?
As another option, you can do look ups like:
class UserAdmin(admin.ModelAdmin):
list_display = (..., 'get_author')
def get_author(self, obj):
return obj.book.author
get_author.short_description = 'Author'
get_author.admin_order_field = 'book__author'
Since Django 3.2 you can use display()
decorator:
class UserAdmin(admin.ModelAdmin):
list_display = (..., 'get_author')
@admin.display(ordering='book__author', description='Author')
def get_author(self, obj):
return obj.book.author
Django: list_display( ) ForeignKey
Try this:
class User_DataAdmin(admin.ModelAdmin):
...
list_display = (..., 'get_click_times', 'get_word')
def get_click_times(self, obj):
return obj.click_data.click_times
get_click_times.short_description = 'Click Times'
def get_word(self, obj):
return obj.click_data.word
get_word.short_description = 'Word'
How to display the foreign key and many-to-many fields in Django admin `list_display`?
You can fetch the related character
s/author
s and then join the names in a comma separated list:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'characters', 'authors')
def characters(self, obj):
return ', '.join([c.name for c in obj.character.all()])
def authors(self, obj):
return ', '.join([a.name for a in obj.author.all()])
We can boost performance by using .prefetch_related(…)
[Django-doc] to fetch all related objects in bulk:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'characters', 'authors')
def characters(self, obj):
return ', '.join([c.name for c in obj.character.all()])
def authors(self, obj):
return ', '.join([a.name for a in obj.author.all()])
def get_queryset(self, request):
return super().get_queryset(request).prefetch_related(
'character', 'author'
)
Since the related_name
is the relation in reverse, and there can be multiple Character
s/Author
s, it makes sense to give these a plural name.
Django Admin can't display attributes in a model with multiple Foreign Keys to another model
Solved: thanks to Iain's answer, should not call attribute and only leave it as icon1
instead of icon1__name
since it calls the __str__
method which returns the name anyway.
django admin list_display not a callable
For the list display, you work with a function, not with a chain of underscore separated field names, so:
class PositionControlAdmin(admin.ModelAdmin):
list_display = ('branch_name', 'position', 'rank', 'valid')
list_filter = ('company_group__branch',)
@admin.display(description='Branch name')
def branch_name(self, object):
return object.company_group.branch.name
Can Django ModelAdmin display foreign key fields in the add and change pages?
Seems that you forgot to add __str__
method (or __unicode__
for python 2) to your models. There's no need to create special methods to just display values of ForeignKey
s.
class franchise(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
def __str__(self): # __unicode__ for py2
return self.name
class ItemAdmin(admin.ModelAdmin):
list_display = ('title', 'franchise', 'description')
How to show foreignkey attributes django admin fields?
If I understood you correctly, This should work.
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {str(self.subject_class)}"
Django admin: list_display/search_fields foreign key of a foreign key in admin view
Add a method to your model admin that takes a person obj
and returns the country label. Then add the method to list_display
.
class PersonAdmin(admin.ModelAdmin):
def country_label(self, obj):
return obj.city.country_code.label
list_display = ('id', 'username', 'city', 'country_label')
list_select_related = ['city__country_code']
ordering = ('username',)
raw_id_fields = ('city',)
search_fields = ['username', 'city__label', 'city__country_code__label']
See the list_display
docs for more info.
Note I have used list_select_related
to reduce the number of SQL queries.
Related Topics
How to Read Realtime Microphone Audio Volume in Python and Ffmpeg or Similar
Installing Python Modules on Ubuntu
How to Make a Call to an Executable from Python Script
How to Fake Terminal Input with Termios.Tiocsti
Python Ta-Lib Install Error, How Solve It
Understanding Python Unicode and Linux Terminal
Why Does Pyimport_Import Fail to Load a Module from the Current Directory
Python Udisks - Enumerating Device Information
Why Is the Subprocess.Popen Argument Length Limit Smaller Than What the Os Reports
Move Files from One Directory to Another with Paramiko
Detect New or Modified Files with Python
Reshape Wide to Long in Pandas
Making Python/Tkinter Label Widget Update
Python Referencing Old Ssl Version
Python Operator Precedence of in and Comparison
Why Does Foo.Append(Bar) Affect All Elements in a List of Lists
Grouping Python Dictionary Keys as a List and Create a New Dictionary with This List as a Value