Filtering select field options in django-admin

2019-08-22 04:28发布

问题:

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 ?

回答1:

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.



回答2:

limit_choices_to with multiple conditions:

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

we can add multiple limit choices option in the model..



回答3:

Limit choice filter with multiple fields with Q object:

from django.db.models import Q

limit_to = Q(username="stack") & Q(is_staff=True) & Q(is_active=True)