1 | initial version |
The process for generating clickable links for foreign keys in the Django admin panel involves the following steps:
In the model that has the foreign key relationship, define the related model using the ForeignKey field.
In the related model, define a str method that returns a string value that will be displayed as the clickable link in the admin panel.
Register both models in the admin.py file, and define a list_display attribute for the model that has the foreign key relationship.
Include the related model's str method in the list_display attribute for the model that has the foreign key relationship, and enclose it in a lambda function.
Here is an example:
# models.py
class Author(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
def __str__(self):
return self.title
# admin.py
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author_name')
def author_name(self, obj):
return obj.author.name
author_name.admin_order_field = 'author__name'
author_name.short_description = 'Author'
admin.site.register(Author)
admin.site.register(Book, BookAdmin)
In this example, the Author
model is related to the Book
model through a foreign key field. We define a __str__
method for both models, and include the Author
model's name
attribute as a display value for the clickable link.
In the BookAdmin
class, we define a list_display
attribute that includes a lambda
function for the author_name
attribute. The lambda
function returns the Author
model's name
attribute, which will be used as the display value for the clickable link in the admin panel.
Finally, we register both models in the admin.py file, and specify the BookAdmin
class as the admin class for the Book
model.