【问题标题】:How to make a filter on my own field in django admin?如何在 django admin 中对我自己的字段进行过滤?
【发布时间】:2013-08-22 01:52:03
【问题描述】:

我添加了一个布尔字段,从时间计算是这样的:

def is_active(self):
    if self.inactive_to and self.available_until:
        if datetime.date.today()>=self.inactive_to and datetime.date.today()<=self.available_until:
            return True
        else:
            return False
    elif self.inactive_to:
        if datetime.date.today()>=self.inactive_to:
            return True
        else:
            return False
    elif self.available_until:
        if datetime.date.today()<=self.available_until:
            return True
        else:
            return False
    else:
        return True
is_active.short_description = 'Available'
is_active.boolean = True

但如果我尝试将其添加到“list_filter”中,则会收到错误消息“'RealtyAdmin.list_filter[0]' 指的是 'is_active',它不指代字段。”

我可以避免它,还是添加将自动计算的模型字段?

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    admin 不是从 django.db.models.fields 子类化的字段。

    这就是'is_active' which does not refer to a Field." 所说的......

    【讨论】:

      【解决方案2】:

      我不够细心,这里https://docs.djangoproject.com/en/1.5/ref/contrib/admin/是关于如何添加自己的过滤器的描述(从1.4开始)

      【讨论】:

        【解决方案3】:

        听起来您混淆了list_displaylist_filter。您的代码用于在list_display 中添加新列,但您的标题和错误消息参考list_filter

        【讨论】:

          【解决方案4】:

          Django ORM 找不到名为 is_active 的数据库字段,因为它是一个 python 函数。 Django 管理员不启用按 python 函数返回的结果进行排序或过滤。 但是,正如您所说,您可以在模型中添加一个包含所需值的字段,然后将其添加到list_filter

          【讨论】:

            猜你喜欢
            • 2020-09-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-04-28
            • 2010-10-26
            • 1970-01-01
            • 2015-12-17
            • 1970-01-01
            相关资源
            最近更新 更多