代码之家  ›  专栏  ›  技术社区  ›  Milano

Django管理列表过滤器-下拉小部件

  •  0
  • Milano  · 技术社区  · 6 年前

    我可以改变 list_filter 要下拉列表的相关对象。问题是当我想过滤相关对象的相关对象时:

    class Match(Model):
        team = models.ForeignKey('Team'...)
        away_team = ... (doesn't matter)
    
    class Team(Model):
        country = models.ForeignKey('Country'...)
    

    Match 对象依据 Team ,我知道:

    list_filter = ['team__country']
    

    dropdown 我用这个过滤器 https://github.com/mrts/django-admin-list-filter-dropdown :

     list_filter[('team',RelatedDropdownFilter)]
    

    当我想过滤的时候 对象依据 Country 他们的 团队 :

    list\u filter=['team\u country']
    

    list_filter = [('team__country',RelatedDropdownFilter)]
    

    看起来和没有一样 RelatedDropdownFilter

    相关下拉滤波器

    class RelatedDropdownFilter(RelatedFieldListFilter):
        template = 'django_admin_listfilter_dropdown/dropdown_filter.html'
    

    模板

    {% load i18n %}
    <script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script>
    <h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3>
    <ul class="admin-filter-{{ title|cut:' ' }}">
    {% if choices|slice:"4:" %}
        <li>
        <select style="width: 95%;"
            onchange="go_from_select(this.options[this.selectedIndex].value)">
        {% for choice in choices %}
            <option{% if choice.selected %} selected="selected"{% endif %}
             value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option>
        {% endfor %}
        </select>
        </li>
    {% else %}
    
        {% for choice in choices %}
                <li{% if choice.selected %} class="selected"{% endif %}>
                <a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a></li>
        {% endfor %}
    
    {% endif %}
    </ul>
    

    你知道我该怎么做吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   orokusaki    6 年前

    您的模板正在检查是否有4个以上的选项:

    {% if choices|slice:”4:” %}
    

    我的猜测是,在您正在查看的测试数据中,只有不超过四个选项。

    只需删除该检查并始终使用 <select> 或者添加更多的测试数据。这些选择是基于现有数据构建的,而不是简单地包含所有可能的值。