我可以在管理员中使用Django模型函数作为字段吗?

时间:2013-04-03 03:44:49

标签: django django-models django-admin

我有一个返回数值的模型函数。我希望能够按该值进行过滤和排序。当我尝试将其添加到list_filter时,Django抱怨该模型没有这样的字段。我可以告诉Django将它视为一个领域吗?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:0)

你是否曾尝试将它用作类属性,但我没有尝试过它?

class SomeModel(models.Model):
    @property
    def list_filter(self):
        """ Do your stuffs here """

答案 1 :(得分:0)

您可以编写自定义过滤器并将其传递到list_filter

from django.contrib.admin import SimpleListFilter

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

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

    def lookups(self, request, model_admin):
        if request.user.is_superuser:
            return (
                ('active', _('Active')),
                ('not_active', _('Not Active')),
            )

    def queryset(self, request, queryset):
        # do something here with queryset

class MyAdmin(admin.ModelAdmin):
    list_filter = (CustomFilter, 'other_model_field')

有关ModelAdmin.list_filter

的详情,请参阅here