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

2022-01-25 00:00:00 python django django-admin

问题描述

我正在寻找一种在过滤查询集的基础上使用 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.

相关文章