您正在寻找ModelAdmin.list_filter。
设置list_filter以激活管理员更改列表页面右侧栏中的过滤器。listfilter可以是字段名称,其中指定的字段应该是BooleanField,CharField,DateField,DateTimeField,IntegerField,ForeignKey或ManyToManyField,例如:
# Add a list filter author to BookAdmin.
# Now you can filter books by author.
class BookAdmin(ModelAdmin):
list_filter = ('author', )
现在,您可以使用@Wolph建议在作者list_display中添加链接。该链接指向按作者过滤的图书清单:
# Add hyperlinks to AuthorAdmin.
# Now you can jump to the book list filtered by autor.
class AuthorAdmin(admin.ModelAdmin):
def authors(self):
return '<a href="/admin/appname/book/?author__id__exact=%d">%s</a>' % (self.author_id, self.author)
authors.allow_tags = True
替代。要保存点击,您还可以直接指向书籍的更改视图:
class Books(models.Model):
title = models.CharField()
author = models.ForeignKey(Author)
def get_admin_url(self):
return "/admin/appname/books/%d/" %self.id
class BookAdmin(admin.ModelAdmin):
def authors(self):
html = ""
for obj in Books.objects.filter(author__id_exact=self.id):
html += '<p><a href="%s">%s</a></p>' %(obj.get_admin_url(), obj.title)
return html
authors.allow_tags = True
list_display = ['title', authors]
免责声明:未经测试,但是如果您解决了错字问题,它将起作用!:)