我遇到了这样的问题:我想限制内联模型管理员中的外键选择,但我想根据此内联对象中指定的某些值来执行此操作。
如何在InlineModelAdmin方法中访问内联对象(不是父对象)(特别是在formfield_for_foreignkey(self, db_field, request, **kwargs)
中)?
答案 0 :(得分:2)
您无法访问任何InlineModelAdmin方法中的内联对象。
唯一的方法是使用自定义ModelForm,该模型在初始化时会收到instance
。请注意,extra
表单用于创建新的内联对象接收和“空” instance
(pk =无)。
from django.forms import ModelForm
from django.contrib.admin import ModelAdmin, TabularInline
class QuestionForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
# do what you want with inline object instance
class Meta:
model = Question
fields = "__all__"
class QuestionInline(TabularInline):
model = Question
form = QuestionForm
class CategoryAdmin(ModelAdmin):
model = Category
inlines = [QuestionInline]
答案 1 :(得分:0)
这对你有用。使用适当的值更改“YourModelAdmin”,“target_field”,“your_custom_condition”和“...”。
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
field = super(YourModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'target_field':
if request and your_custom_condition:
field.queryset = field.queryset.filter(...)
return field