如何在raw_id外键的内联表单中自定义spyglas查询?
我试着重写formfield_for_foreignkey
,但没有效果,我想这是因为它是用于下拉外键,而不是raw_id。我也尝试了一个自定义的小部件,但似乎在内联上不起作用。
发布于 2018-02-16 23:01:04
因此,经过大量的挖掘,这就是我想出来的。
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
所以spyglass的东西是一个ForeignKeyRawIdWidget
,你需要用一个自定义的来覆盖默认值。小部件上的url_parameters
函数用于构建查询,该查询填充可用的对象外键列表。
发布于 2018-05-11 18:29:12
要做到以下几点就足够了:
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
https://stackoverflow.com/questions/48834334
复制相似问题