Django 管理过滤器调整
我想在列表页面上使用 django 的管理过滤器。 我拥有的模型是这样的:
class Location(model):
name = CharField()
class Inquiry(Model):
name = CharFiled()
location = ManyToManyField(Location)
现在我想过滤查询,仅显示那些包含与特定位置对象关系的查询。如果我使用
class InqAdmin(ModelAdmin):
list_filter = ['location', ]
admin.site.register(Inquiry, InqAdmin)
管理页面,则会显示所有位置
的列表并允许进行过滤。
我想要得到的是仅获取那些与它们相关的查询
的位置的列表(这样我在过滤后就不会得到空列表结果)。
这怎么能做到呢?
I want to use django's admin filter on the list page.
The models I have are something like this:
class Location(model):
name = CharField()
class Inquiry(Model):
name = CharFiled()
location = ManyToManyField(Location)
Now I want to filter Inquiries, to display only those that contain relation to specific Location object. If I use
class InqAdmin(ModelAdmin):
list_filter = ['location', ]
admin.site.register(Inquiry, InqAdmin)
the admin page displays me the list of all Locations
and allows to filter.
What I would like to get, is to get list of only those locations that have some Inquiries
in relation to them (so I don't ever get the empty list result after filtering).
How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为位置创建一个自定义管理器,该管理器仅返回与其关联的查询的位置。如果您将其设为默认管理器,管理员将使用它。
唯一需要注意的是,您需要创建另一个返回所有位置的管理器,并在您想要检索没有关联查询的位置时在应用程序的其余部分中使用它。
Django 文档中的管理器部分非常好,应该是您完成此设置所需的一切。
编辑:
sienf 提出了一个很好的观点。实现此目的的另一种方法是定义 django.contrib.admin.SimpleListFilter 的子类,并编写
queryset
方法来过滤掉具有空位置的查询。请参阅 https://docs。 djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filterYou could create a custom manager for Locations that only returns Locations that have an Inquiry associated with them. If you make this the default manager, the admin will use it.
Only caveat is that you'll need create another manager that returns all Locations and use that in the rest of your app whenever you want to retrieve Locations that don't have an associated Inquiry.
The managers section in the Django docs is quite good, and should be all you need to get this set up.
EDIT:
sienf brings up a good point. Another way to accomplish this would be to define a subclass of
django.contrib.admin.SimpleListFilter
, and write thequeryset
method to filter out Inquiries with empty Locations. See https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter