在我的 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/