Django Admin - 根据正在编辑的当前对象筛选选择字段

时间:2016-02-16 06:22:28

标签: django django-forms django-admin

我试图从选择字段中排除正在编辑的当前对象,以从同一模型中选择父对象。例如:

from django import forms
from django.contrib import admin

class RelationForm(forms.ModelForm):    
    parent = forms.ModelChoiceField(queryset=Ingredient.objects.exclude(id=current_ingredient_id))  

    def save(self, commit=True):
        parent = self.cleaned_data.get('parent', None)
        # ...do something with extra_field here...
        return super(RelationForm, self).save(commit=commit)

    class Meta:
        model = IngredientRelations
        exclude = ['description']

@admin.register(Ingredient)
class IngredientAdmin(admin.ModelAdmin):
    form = RelationForm

    fieldsets = (
        (None, {
             'fields': ('name', 'slug', 'description', 'parent',),
        }),
    ) 

困难来自于正在编辑当前对象,然后在RelationForm中为查询集参数获取其主键。

我尝试在IngredientAdmin中使用ModelAdmin.formfield_for_foreignkeyModelAdmin.formfield_for_choice_field但没有运气。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

执行此操作的规范方法是使用当前编辑的实例ID更新queryset方法中的__init__

class RelationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(RelationForm, self).__init__(*args, **kwargs)
        if self.instance.id:
            self.fields['parent'].queryset = Ingredient.objects.exclude(id=self.instance.id)

    class Meta:
        model = IngredientRelations
        exclude = ['description']

最初在此答案中看到:https://stackoverflow.com/a/1869917/484127