Python 如何在 Django 管理员中过滤 filter_horizontal?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22968631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter filter_horizontal in Django admin?
提问by normic
I'm looking for a way to use filter_horizontal on the base of a filtered queryset.
我正在寻找一种在过滤查询集的基础上使用 filter_horizontal 的方法。
I've tried to use it with a custom manager:
我尝试将它与自定义管理器一起使用:
In models.py:
在models.py中:
class AvailEquipManager(models.Manager):
def get_query_set(self):
return super(AvailEquipManager, self).get_query_set().filter(id=3)
class Equipment(models.Model):
description = models.CharField(max_length=50)
manufacturer = models.ForeignKey(Manufacturer)
[...]
objects = models.Manager()
avail = AvailEquipManager()
def __unicode__(self):
return u"%s" % (self.description)
In admin.py:
在 admin.py 中:
class SystemAdmin(admin.ModelAdmin):
filter_horizontal = ('equipment',) # this works but obviously shows all entries
#filter_horizontal = ('avail',) # this does not work
So the questions is, how can I reduce the left side of the filter_horizontal to show only specific items?
所以问题是,如何减少 filter_horizontal 的左侧以仅显示特定项目?
采纳答案by normic
I found a solution by adapting the answer to a different question which I found in Google Groups
我通过调整我在Google Groups 中找到的不同问题的答案找到了解决方案
It works with a custom ModelForm like so:
它与自定义 ModelForm 一起使用,如下所示:
Create a new forms.py:
创建一个新的forms.py:
from django import forms
from models import Equipment
class EquipmentModelForm(forms.ModelForm):
class Meta:
model = Equipment
def __init__(self, *args, **kwargs):
forms.ModelForm.__init__(self, *args, **kwargs)
self.fields['equipment'].queryset = Equipment.avail.all()
Then in admin.py:
然后在 admin.py 中:
class SystemAdmin(admin.ModelAdmin):
form = EquipmentModelForm
filter_horizontal = ('equipment',)
Hope this helps someone else out sometime.
希望这可以帮助其他人。