自定义list_filter结果

时间:2015-11-13 13:37:46

标签: django django-admin

我想限制django" list_filter"在Django admin中显示。

根据我的模型,我只希望它显示类别中的类别(在过滤器中)并包含层整数" 1"。

这可能吗?

class Category(models.Model):
    category_name = models.CharField(max_length=100, blank=False)
    tier = models.IntegerField(blank=false)
    def __str__(self):
        return self.category_name

class Product(models.Model):
    name = models.CharField ("Name", max_length=400)
    link = models.URLField("Link", max_length=900)
    store = models.ForeignKey(Store)
    category = models.ManyToManyField(Category, blank=True)

在管理员中,我有:

list_filter = ('category')

我相信我需要将这些内容纳入其中?

category=Category.objects.get(tier__iexact='1')

1 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

from django.contrib import admin
from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _


class CategoryListFilter(admin.SimpleListFilter):
    title = _('Category')
    parameter_name = 'category'

    def lookups(self, request, model_admin):
        categories = Category.objects.filter(tier=1)
        for obj in categories:
            yield (str(obj.pk), smart_text(obj))

    def queryset(self, request, queryset):

        if self.value():
            return queryset.filter(category__id=self.value())


class ProductAdmin(admin.ModelAdmin):
    list_filter = (CategoryListFilter,)

文档:https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter