Django admin 根据另一个字段值过滤一个外部字段

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

在我的 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 Smart Selects它具有称为 Grouped Selects 的功能

引自自述文件:

If you have the following model:

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

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

And you want to group countries by their continent in the HTML select list, you can use a GroupedForeignKey:

from smart_selects.db_fields import GroupedForeignKey

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

关于Django admin 根据另一个字段值过滤一个外部字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52862289/

相关文章:

python - 如何得到正确的十进制结果

python - 如何在 if 和 else 语句(在 python 中)中定义 for 循环的结果?

python - 根据ManyToMany关系存在过滤Django QuerySet

Django——过滤时将多对多对象集视为一个实体

python - 自定义身份验证方法或者其他方法可以做到同样的事情? Django

python - 带条件的嵌套对象列表

python - 如何将json转换为对象?

python - Django - Decimal 类型的对象不可 JSON 序列化并转换为 View 中的模型数据

Django 模型 : Automatic value assignment to a field based on another field value

python - 在我尝试安装 pip install -r requirements.txt 文件后,Docker 构建出现错误