重命名Django过滤器中的字段名称以进行显示

时间:2018-07-13 18:00:05

标签: django django-filter

在django-filters中的django应用上显示时,是否可以重命名字段名称? filter.py

import django_filters as df
from .models import Books


class BooksListFilter(df.FilterSet):
  class Meta:
    model = Books
    fields = ['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 %}

2 个答案:

答案 0 :(得分:3)

您可以显式定义字段,并使用this one-liner will do everything you need参数将字段与模型链接:

class BooksListFilter(df.FilterSet):
  new_name = df.CharFilter(name='name')
  class Meta:
    model = Books
    fields = ['new_name']

答案 1 :(得分:0)

如果您要更改标签,请使用:

  class BooksListFilter(django_filters.FilterSet):
  name = django_filters.CharFilter(label='Book Name')
  class Meta:
    model = Books
    fields = ['name']

如果您想更改过滤的字段名称(表示您要在数据库的其他字段中搜索)

neverwalkaloner回答

class BooksListFilter(django_filters.FilterSet):
  new_name = django_filters.CharFilter(field_name='name')
  class Meta:
    model = Books
    fields = ['new_name']