26

给定以下模型

class AnotherModel(models.Model):
    n = models.IntegerField()

class MyModel(models.Model):
    somefield = models.ForeignKey(AnotherModel)

和管理员

class MyModelAdmin(admin.ModelAdmin):        
    list_filter = ('somefield',)

如何过滤实例AnotherModel以仅在我的管理过滤器中显示具有给定n值的实例?

我需要类似的东西:

筛选

由某个领域

全部

[给定 n 的 AnotherModel 实例列表]

4

4 回答 4

34

请参阅ModelAdmin.querysetModelAdmin.formfield_for_foreignkey。从文档:

ModelAdmin 上的 queryset 方法返回可以由管理站点编辑的所有模型实例的 QuerySet。覆盖此方法的一个用例是显示登录用户拥有的对象:

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

ModelAdmin 上的 formfield_for_foreignkey 方法允许您覆盖外键字段的默认表单字段。例如,要根据用户返回此外键字段的对象子集:

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

这使用 HttpRequest 实例过滤 Car 外键字段以仅显示 User 实例拥有的汽车。

[更新]

抱歉,我没有阅读“过滤器”部分。在 Django >= 1.4 中,您可以 django.contrib.admin.SimpleListFilterlist_filter 参数列表中传递 的子类,您可以使用它来覆盖查找和查询集方法。

from datetime import date

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

class DecadeBornListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('decade born')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'decade'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('80s', _('in the eighties')),
            ('90s', _('in the nineties')),
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or '90s')
        # to decide how to filter the queryset.
        if self.value() == '80s':
            return queryset.filter(birthday__gte=date(1980, 1, 1),
                                birthday__lte=date(1989, 12, 31))
        if self.value() == '90s':
            return queryset.filter(birthday__gte=date(1990, 1, 1),
                                birthday__lte=date(1999, 12, 31))

class PersonAdmin(admin.ModelAdmin):
    list_filter = (DecadeBornListFilter,)
于 2012-09-21T00:14:35.770 回答
7

编辑-已指出此方法存在问题,请参见下文

你可以这样做:

假设您有一个名为 Animal 的模型,它具有一个名为 Species 的模型的 ForeignKey 字段。在特定的管理列表中,您希望仅允许在动物过滤器选项中显示某些物种。

首先,在 Animal 的 ModelAdmin 中指定一个名为 SpeciesFilter 的自定义 ListFilter:

class AnimalAdmin(ModelAdmin):
    list_filter = (('species', SpeciesFilter),)

然后定义 SpeciesFilter:

from django.contrib.admin.filters import RelatedFieldListFilter

class SpeciesFilter(RelatedFieldListFilter):
    def __init__(self, field, request, *args, **kwargs):
        """Get the species you want to limit it to.
        This could be determined by the request,
        But in this example we'll just specify an
        arbitrary species"""
        species = Species.objects.get(name='Tarantula')

        #Limit the choices on the field
        field.rel.limit_choices_to = {'species': species}

        #Let the RelatedFieldListFilter do its magic 
        super(SpeciesFilter, self).__init__(field, request, *args, **kwargs)

那应该这样做。

于 2013-02-18T15:58:47.317 回答
2

我找到了另一种类似于@seddonym 的方法,但不会弄乱缓存。它基于这个 Django 代码,但使用了未记录的方法field_choices,在未来的 Django 版本中可能会发生变化。@seddonym 案例的代码是:

from django.contrib.admin.filters import RelatedFieldListFilter

class SpeciesFilter(RelatedFieldListFilter):
    def field_choices(self, field, request, model_admin):
        return field.get_choices(include_blank=False, limit_choices_to={'name': 'Tarantula'})

或者在我的情况下,工作代码是:

from django.contrib.admin.filters import RelatedFieldListFilter

class UnitFilter(RelatedFieldListFilter):
    def field_choices(self, field, request, model_admin):
        return field.get_choices(include_blank=False, limit_choices_to={'pk__in': request.user.administrated_units.all()})

于 2019-07-15T09:58:23.863 回答
1

我必须从 db 表创建我的查找字段。我创建了如下自定义过滤器类,并仅显示登录用户的相关值并相应地过滤:

class ShiftFilter_Org(admin.SimpleListFilter):
title = 'Organisation'
parameter_name = 'org'

def lookups(self, request, model_admin):
"""Get the organisations you want to limit"""
    qs_org = Organisation.objects.filter(users=request.user)
    list_org = []
    for og in qs_org:
        list_org.append(
            (og.id, og.name)
        )
    return (
        sorted(list_org, key=lambda tp:tp[1])
    )

def queryset(self, request, queryset):
    if self.value():
        return queryset.filter(org=self.value())

有关更多信息,请访问充分利用 Django Admin 过滤器

于 2018-05-31T13:29:03.380 回答