【问题标题】:django-filter chained selectdjango过滤器链式选择
【发布时间】:2019-02-01 19:21:09
【问题描述】:

我正在使用 django-filters lib https://django-filter.readthedocs.io/en/master/index.html。我需要在我的过滤器中创建链接选择下拉列表。 我知道如何使用简单的 django-forms 来制作它,例如https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html。 当用户选择地区时,我需要显示该地区的城市吗?有人知道如何构建这样的过滤器吗?

【问题讨论】:

    标签: python django django-filter


    【解决方案1】:

    django-smart-selects 与您执行过滤的方式相结合。

    此软件包允许您通过向模型添加自定义外键或多对多字段来快速过滤或分组“链接”模型。这将使用 AJAX 查询仅加载适用的链式对象。

    类似于Region -> City 的原始问题,documentation's exampleContinent -> Country,它完全符合需要。

    一旦您选择了一个大洲,如果您只希望该大洲的国家/地区可用,您可以在 Location 模型上使用 ChainedForeignKey

    class Location(models.Model):
        continent = models.ForeignKey(Continent)
        country = ChainedForeignKey(
            Country,
            chained_field="continent",  # Location.continent
            chained_model_field="continent",  # Country.continent
            show_all=False,  # only the filtered results should be shown
            auto_choose=True,
            sort=True)
    

    相关问题:

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2022-11-12
      • 2015-08-26
      • 1970-01-01
      • 2019-02-07
      • 2022-01-01
      • 1970-01-01
      • 2013-05-26
      • 2018-02-17
      相关资源
      最近更新 更多