Search code examples
djangodjango-modelsdjango-formsdjango-admindjango-admin-filters

Filtering select field options in django-admin


I am using django-xadmin for one of my project which is based on django-admin. I need help in a case. Suppose, i have two models like this -

class Foo(models.Model):
    CHOICES = (
        ('a', 'Option A'),
        ('b', 'Option B')
    )
    status = models.CharField(max_length=10, choices=CHOICES)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    remarks = models.CharField(max_length=200)

In xadmin, when i try to add Bar via default form provided by xadmin, in the select Field Foo, all Foos (both with Option A and Option B) become available to select. I want to filter the options and only provide, say, Foos of Option A.

How can i do that ? Is there any method in xadmin, i should call or customize to achieve it ?


Solution

  • Take a look at limit_choices_to

    EDIT

    Consider this example from the doc:

    staff_member = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        limit_choices_to={'is_staff': True},
    )
    

    causes the corresponding field on the ModelForm to list only Users that have is_staff=True. This may be helpful in the Django admin.

    Therefore, this is an easy way of adding restrictions on corresponding fields.