Reputation: 6997
Am working on a django admin interface and I have a model which has a foreign key. In that field, am getting a drop down menu when the admin pages are viewed. Is there a way to filter the drop down result only where is_active=1 for example?
Regards,
Upvotes: 0
Views: 2027
Reputation: 5181
According to the docs
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(is_active=1)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
If you need access to current object check this How do I get the actual object id in a Django admin page (inside formfield_for_foreignkey)?
Upvotes: 0
Reputation: 18972
limit_choices_to is what you are after.
If you only want the limited selection in your ModelAdmin
you should tweak your ModelForm
accordingly.
Something like this should do it:
class YourAdminForm(forms.ModelForm):
class Meta:
model = YourModel
def __init__(self, *args, **kwargs):
super(YourAdminForm, self).__init__(*args, **kwargs)
qs = self.fields['your_fk_field'].queryset
self.fields['your_fk_field'].queryset = qs.filter(is_active=1)
Upvotes: 3