重命名 django-filters 中的字段名称以供显示

Ais*_*que 3 django django-filter

在 django-filters 中的 django 应用程序上显示时,有没有办法重命名字段名称?过滤器.py

import django_filters as df
from .models import Books


class BooksListFilter(df.FilterSet):
  class Meta:
    model = Books
    fields = ['name']
Run Code Online (Sandbox Code Playgroud)

我在数据库中的字段名称是“name”,但我希望它在 Django 应用程序中显示为“BookName”。我怎样才能做到这一点?

编辑:模板文件

{% load bootstrap3 %}
{% load render_table from django_tables2 %}
{% load crispy_forms_tags %}
{% block content %}

{% render_table table %}


<form action="" method="get">
{% crispy filter.form filter.form.helper %}
<input type="submit" value="Filter Results"/>
</form>

{% endblock content %}
Run Code Online (Sandbox Code Playgroud)

nev*_*ner 7

您可以使用name参数显式定义字段并将字段与模型链接:

class BooksListFilter(df.FilterSet):
  new_name = df.CharFilter(field_name='name')
  class Meta:
    model = Books
    fields = ['new_name']
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,文档与最新的 2.0 版本略有过时,`name` 参数应该是 `field_name`。 (5认同)