Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we search many to many field in django admin search field

Here, I have a many to many field define in Django model and I want to search that many to many field in my Django admin search field. As we cannot place many to many field in the 'search_fields=[]' of the customise djangomodelAdmin class.If anyone have the solution please give some suggestions.

like image 751
Shubham Bansal Avatar asked Aug 20 '18 13:08

Shubham Bansal


1 Answers

Say we have two models Item and SubItem:

class SubItem(Model):
    name = CharField(max_length=128)

class Item(Model):
    subitems = ManyToManyField(SubItem)

We can search on the name of related SubItem objects, by using double underscores (__) in the search_fields of the ModelAdmin:

class ItemAdmin(admin.ModelAdmin):
    search_fields = ['subitems__name']

If one thus enters a query, then the search will take place on the name of the SubItems, and Items that contain such subitem, will be returned.

like image 101
Willem Van Onsem Avatar answered Oct 23 '22 00:10

Willem Van Onsem