Shubham Bansal
Shubham Bansal

Reputation: 175

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.

Upvotes: 9

Views: 6430

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476669

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.

Upvotes: 15

Related Questions