Django Admin Cookbook-34如何在Django Admin中过滤外联字段
返回目录
34.如何在Django Admin中过滤外联字段?
你的Hero模型有个外联字段到Category模型。因此,所有Category对象将显示在该外联字段的下拉列表中。如果你只想在特定的Category子集中选择,你可以通过重写formfield_for_foreignkey来实现:
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "category":
kwargs["queryset"] = Category.objects.filter(name__in=['God', 'Demi God'])
return super().formfield_for_foreignkey(db_field, request, **kwargs)