Filtering select field options in django-admin

北城以北 提交于 2019-12-13 02:48:14

问题


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)


来源:https://stackoverflow.com/questions/46833318/filtering-select-field-options-in-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!