python - 如何在 Django 管理中过滤 filter_horizo​​ntal?

标签 python django django-admin

我正在寻找一种在过滤查询集的基础上使用 filter_horizo​​ntal 的方法。

我尝试将它与自定义管理器一起使用:

在 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)

在 admin.py 中:

class SystemAdmin(admin.ModelAdmin):
    filter_horizontal = ('equipment',) # this works but obviously shows all entries
    #filter_horizontal = ('avail',)     # this does not work

所以问题是,我怎样才能减少 filter_horizo​​ntal 的左侧以仅显示特定项目?

最佳答案

我通过调整我在 Google Groups 中找到的不同问题的答案找到了解决方案

它像这样与自定义 ModelForm 一起工作:

新建一个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()

然后在admin.py中:

class SystemAdmin(admin.ModelAdmin):
    form = EquipmentModelForm
    filter_horizontal = ('equipment',) 

希望这有时能帮助其他人。

关于python - 如何在 Django 管理中过滤 filter_horizo​​ntal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22968631/

相关文章:

python - 在 Django admin 中将模型字段显示为只读

python - 检查ManyToMany字段中的对象是否为Django Rest框架

Python 迭代器——如何在新样式类中动态分配 self.next?

python - 如何使用LinearRegression获得重要性F,R平方?

javascript - Django 获取优惠券代码并检查该代码另一列中的 bool 值 ("is available")

django - 在django-admin内联表单上验证删除

python - 无法将用户字段内联到 UserProfile 管理选项卡 - 'auth.User' 没有外键到 'MyApp.UserProfile'

Django:从管理员的 form.clean() 访问请求对象

python - 为什么函数定义中的默认变量差一个?

python - 使用共享基本名称的 Python 包