栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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.idclass 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]

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640305.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号