在django admin中过滤下拉列表值

时间:2011-07-05 10:54:15

标签: python django django-models django-admin

class Foo(models.Model):
    title = models.TextField()
    userid = models.IntegerField()
    image = models.CharField(max_length=100)
    def __unicode__(self):
       return self.title

class Bar(models.Model):
    foo = models.ForeignKey(Foo, related_name='Foo_picks', unique=True)
    added_on = models.DateTimeField(auto_now_add=True)

在Django admin add_view中:

def add_view(self, *args, **kwargs):
    self.exclude = ("added_on",)
    self.readonly_fields = ()
    return super(Bar, self).add_view(*args, **kwargs)

因此,管理添加视图中的字段显示为foo这是一个下拉列表并显示所有标题。某些title Foo仍为空或“。因此,下拉列表有很多空值,因为它的标题是空的。我想过滤掉那些空值。

4 个答案:

答案 0 :(得分:20)

您可以为ModelAdmin提供自己的表单,并为foo字段提供自定义查询集。

from django import forms
from django.contrib import admin

#Create custom form with specific queryset:
class CustomBarModelForm(forms.ModelForm):
    class Meta:
        model = Bar
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(CustomBarModelForm, self).__init__(*args, **kwargs)
        self.fields['foo'].queryset = Foo.objects.filter(title__isnull=False)# or something else

# Use it in your modelAdmin
class BarAdmin(admin.ModelAdmin):
    form = CustomBarModelForm

像这样......

docs

答案 1 :(得分:4)

对于django 1.6:

对于外键: https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#ModelAdmin.formfield_for_foreignkey

class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "title":
        kwargs["queryset"] = Foo.objects.filter(title__isnull=False)
    return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

答案 2 :(得分:1)

您可以继承您自己的model.ModelAdmin并为您的ChoiceField创建自定义字段...

class CustomForm(model.ModelForm):

    class Meta:
        model = Foo

    foo = forms.ChoiceField(widget=forms.Select, initial=self.foo_queryset)

    def foo_queryset(self):
        return Foo.objects.filter(xy)...

class FooAdmin(model.ModelAdmin):
    form = CustomForm

答案 3 :(得分:0)

我在根据在其他字段中的选择寻找在管理界面中过滤下拉选项的解决方案时偶然发现了这个问题 - 不是基于页面加载时的预过滤列表。我找到的解决方案是这个库:https://github.com/digi604/django-smart-selects这是一个使用ajax调用并允许链过滤到多个级别的应用程序。对我来说就像一个魅力。 -HTH