[Django]-Filter foreignkey field in django admin

63πŸ‘

βœ…

Use the render_change_form method:

class CompanyAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
         context['adminform'].form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
         return super(CompanyAdmin, self).render_change_form(request, context, *args, **kwargs)
πŸ‘€BenH

68πŸ‘

I actually prefer to do it in get_form like so:

Django < 2:

class CompanyAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(CompanyAdmin, self).get_form(request, obj, **kwargs)
        form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
        return form

Django >= 2

class CompanyAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(CompanyAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
        return form
πŸ‘€Moritz

25πŸ‘

look here http://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
    ...
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "category":
            kwargs["queryset"] = Category.objects.filter(name__in=['God', 'Demi God'])
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
πŸ‘€slavugan

6πŸ‘

In Django 3 it is easy :

class CompanyAdmin(admin.ModelAdmin):
    list_display = ('name','theme')
    list_filter = ('theme__name',)

admin.site.register(Company,CompanyAdmin)

This will show you a filter on the right of your screen with the list of your theme’s name.

πŸ‘€G.Lebret

4πŸ‘

Another option is to create a custom model form where the queryset attribute of the theme field will be fine tuned to meet your needs.

class CompanyForm(ModelForm):
    class Meta:
        model = CompanyForm
        fields = __all__ # or a tuple of fields

    def __init__(self, *args, **kwargs):
        super(CompanyForm, self).__init__(*args, **kwargs)
        if self.instance: # Editing and existing instance
            self.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')

This model form can be also reused outside of the django admin area.

πŸ‘€Raiyan

2πŸ‘

I faced with the need to add filter to the foreignKey queryset of the parent ModelAdmin class (which all other ModelAdmins inherit from), that is, I can’t know exactly which model I need, this is my solution: db_field.related_model.objects.filter()

class TSModelAdmin(admin.ModelAdmin):
   exclude = ('site',)
    ...

      def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.related_model:
            kwargs["queryset"] = 
            db_field.related_model.objects.filter(site=request.user.user_profile.site)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

used django version 2.2.10

πŸ‘€Webdma

0πŸ‘

A bit unrelated, but similar to this so I’ll post this here.

I was looking for a way to remove the NULL choice selection on a ModelForm foreignkey field. I first thought I could filter the queryset as is done in other answers here, but that didn’t work.

I found that I can filter the entry where the pk value is NULL like this in the get_form method:


class CompanyAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # remove null choice
        form.base_fields["theme"].choices = ((pk, display) for pk, display in form.base_fields["theme"].choices if pk)
        return form
πŸ‘€monkut

Leave a comment