您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Django管理面板中列出所有与外键相关的对象?

如何在Django管理面板中列出所有与外键相关的对象?

您正在寻找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]

免责声明:未经测试,但是如果您解决了错字问题,它将起作用!:)

请注意,这些链接也可以在管理员的其他位置插入。将其添加到窗口小部件时,可以从更改视图转到更改视图。

Go 2022/1/1 18:43:24 有482人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶