您正在寻找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 建议在作者列表显示中添加一个链接。此链接指向按作者过滤的书单:
# 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]
免责声明:未经测试,但如果您修复错字,它会起作用!:)
请注意,这些链接也可以在管理员的其他点注入。当您将其添加到小部件时,您可以从更改视图转到更改视图。