Dhanushka Amarakoon
Dhanushka Amarakoon

Reputation: 3762

Django admin limit foreign key filters to entries within the table

I have a couple models as below.

class Department(models.Model):
        id = models.CharField(max_length=100,primary_key=true)
        name = models.CharField(max_length=100)

class User(models.Model):
    id = models.CharField(max_length=100)
    dept= models.ForeignKey(Department,on_delete=models.SET_NULL,null=True)

class UserDisplay(VersionAdmin):
    list_display = ['id','dept'] 
    list_filter=['dept']

Say I have about 100 departments and only 3 Users. If I click on filter on the Django admin panel for the User model it shows all 100 departments. How can I limit the filters only to show the 3 departments used by this table ?

Upvotes: 2

Views: 404

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can use RelatedOnlyFieldListFilter for this:

class UserDisplay(dmin.ModelAdmin):
    list_display = ['id','dept'] 
    list_filter=[('dept', admin.RelatedOnlyFieldListFilter)]

See details here.

Upvotes: 4

Related Questions