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.
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 SubItem
s, and Item
s that contain such subitem, will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With