2016-02-16 47 views
3

我試圖從選擇字段中排除當前正在編輯的對象以從同一模型中選擇一個父對象。例如: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

執行此操作的規範方法是使用當前編輯的實例ID更新__init__方法中的queryset

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