【问题标题】:Django admin filter a foreign field based on another field valueDjango admin 根据另一个字段值过滤一个外部字段
【发布时间】:2019-03-22 13:41:22
【问题描述】:

在我的 django 应用程序的管理面板中,当我为我的表添加/编辑表单时,我有两个外键列(组合),main_id 和 Test_id。

我会根据 main_id 字段选择中的预览选择过滤 test_id 字段中包含的结果。

在我的 admin.py 中我尝试:

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "test_id":
        kwargs["queryset"] = temp_case.objects.filter(main_id = <here i need the value selected on main_id combo>)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

但我不知道我必须在''中写什么。

我尝试了 main_id__id 或 main_id.id 但不正确。

如何检索 main_id 组合中的选择值并将其传递给我的方法?

提前致谢

【问题讨论】:

    标签: django python-3.x django-models django-admin


    【解决方案1】:

    您可以尝试使用Django Smart Selects 它具有称为Grouped Selects 的功能

    引用自述文件:

    如果您有以下型号:

    class Country(models.Model):
        continent = models.ForeignKey(Continent)
    
    class Location(models.Model):
        continent = models.ForeignKey(Continent)
        country = models.ForeignKey(Country)
    

    并且您想在 HTML 选择中按大洲对国家/地区进行分组 列表,您可以使用 GroupedForeignKey:

    from smart_selects.db_fields import GroupedForeignKey
    
    class Location(models.Model):
        continent = models.ForeignKey(Continent)
        country = GroupedForeignKey(Country, "continent")
    

    【讨论】:

      猜你喜欢
      • 2014-07-03
      • 2012-07-21
      • 1970-01-01
      • 2011-03-14
      • 2016-07-20
      • 2022-08-15
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多