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

How to filter filter_horizontal in Django admin?(如何在 Django 管理员中过滤 filter_horizo​​ntal?)

本文介绍了如何在 Django 管理员中过滤 filter_horizo​​ntal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a way to use filter_horizontal on the base of a filtered queryset.

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

I've tried to use it with a custom manager:

在 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 的左侧以仅显示特定项目?

So the questions is, how can I reduce the left side of the filter_horizontal to show only specific items?

推荐答案

我找到了一个解决方案,方法是调整我在 Google 群组

I found a solution by adapting the answer to a different question which I found in Google Groups

它可以像这样与自定义 ModelForm 一起使用:

It works with a custom ModelForm like so:

创建一个新的forms.py:

Create a new 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中:

Then in admin.py:

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

希望这可以帮助其他人.

Hope this helps someone else out sometime.

这篇关于如何在 Django 管理员中过滤 filter_horizo​​ntal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Django 管理员中过滤 filter_horizo​​ntal?

基础教程推荐