如何在Django admin中过滤filter_horizo​​ntal? [英] How to filter filter_horizontal in Django admin?

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

问题描述

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

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

在models.py中:

  class AvailEquipManager(models.Manager):def get_query_set(self):返回super(AvailEquipManager,self).get_query_set().filter(id = 3)设备类(models.Model):描述= models.CharField(max_length = 50)制造商=模型.ForeignKey(制造商)[...]对象=模型.Manager()可用= AvailEquipManager()def __unicode __(自己):返回u%s"%(self.description) 

在admin.py中:

  SystemAdmin(admin.ModelAdmin)类:filter_horizo​​ntal =('equipment',)#这可行,但显然会显示所有条目#filter_horizo​​ntal =('avail',)#这不起作用 

问题是,如何缩小filter_horizo​​ntal的左侧以仅显示特定项目?

我在

In 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?

解决方案

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

It works with a custom ModelForm like so:

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

Then in admin.py:

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

Hope this helps someone else out sometime.

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆