如何使用过滤器在django-admin中显示数据库? [英] How to show database in django-admin using filters by default?

查看:202
本文介绍了如何使用过滤器在django-admin中显示数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我看到它(保存更改或首次打开数据库时),我都需要默认筛选数据库。
有人可以告诉我如何做吗?

解决方案

这可以通过自定义自定义管理员



说你有一个类叫做 Book

  class Book(models.Model) :
title = models.CharField(max_length = 100)
author = models.CharField(max_length = 50)

您希望书对象的管理页面只显示Roald Dahl的书籍,那么您可以添加一个自定义管理器:

 $ code class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager,self).get_query_set()。filter(author ='Roald Dahl')

class Book(models.Model):
title = models.CharField(max_length = 100)
author = models.CharField(max_length = 50)

objects = models.Manager()
dahl_objects = DahlBookManager()

然后你只需要指定你的 ModelAdmin 应该使用 dahl_objects 管理器,这是解释 here


I need to filter database by default every time that I see it (when I save changes or when I open database first time). Can anybody tell me how to do it?

解决方案

This is possible with custom custom Managers:

Say you have a class called Book:

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)

And you want the admin pages for book objects to only show books by Roald Dahl, then you can add a custom manager:

class DahlBookManager(models.Manager):
    def get_query_set(self):
        return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)

    objects = models.Manager()
    dahl_objects = DahlBookManager()

Then you just need to specify that your ModelAdmin should use the dahl_objects manager, which is explained here.

这篇关于如何使用过滤器在django-admin中显示数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆