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_foreignkey和ModelAdmin.formfield_for_choice_field,但沒有運氣。
任何想法?