如何在内联表单中为raw_id外键自定义spyglass查询?
我尝试覆盖formfield_for_foreignkey
,但这没有做任何事情,我认为这是因为它是用于下拉外键而不是raw_id。我也尝试了一个自定义小部件,但似乎并不适用于内联。
答案 0 :(得分:1)
所以经过大量的挖掘,这就是我想出来的。
from django.admin import widgets
class ItemSubRecipeRawIdWidget(widgets.ForeignKeyRawIdWidget):
def url_parameters(self):
res = super(ItemSubRecipeRawIdWidget, self).url_parameters()
# DO YOUR CUSTOM FILTERING HERE!
res['active'] = True # here I filter on recipe.active==True
return res
class ItemSubRecipeInline(admin.TabularInline):
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
field = super(ItemSubRecipeInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'recipe':
field.widget = ItemSubRecipeRawIdWidget(rel=ItemSubRecipe._meta.get_field('recipe').rel, admin_site=site)
return field
因此,间谍玻璃是ForeignKeyRawIdWidget
,您需要使用自定义覆盖默认值。小部件上的url_parameters
函数是用于构建填充可用对象外键列表的查询的。
答案 1 :(得分:1)
是否应该做以下事情:
class ItemSubRecipeInline(admin.TabularInline):
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
field = super(ItemSubRecipeInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'recipe':
field.widget.rel.limit_choices_to = {'your_field_to_filter': True}
return field