本文介绍了如何在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的左侧以仅显示特定项目?

我在

它可与自定义ModelForm一起使用,如下所示:

创建一个新表格.py:

Django导入表单中的

 从型号进口设备类EquipmentModelForm(forms.ModelForm):类Meta:型号=设备def __init __(self,* args,** kwargs):form.ModelForm .__ init __(自身,* args,** kwargs)self.fields ['equipment'].queryset = Equipment.avail.all() 

然后在admin.py中输入

:

  SystemAdmin(admin.ModelAdmin)类:表格= EquipmentModelFormfilter_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:

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

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:10