[Answered ]-Django search with AND operator many to many relationship

1👍

You get the correctly filtered VenueMenus, but the related MenuItems aren’t filtered automatically because the filter is for VenueMenu and not MenuItem.

To filter the related MenuItems in the serializer, you’ll have to do a filtered prefetch using Prefetch like so:

from django.db.models import Prefetch


menu_item_search = VenueMenu.objects.filter(
    venue_filter & menu_item_filter
).prefetch_related(
    Prefetch(
        'menu_item',
        queryset=MenuItem.objects.filter(name__icontains=request.GET.get('search_name'))
    )
)

Also to improve this further, you can also select the related Venue using select_related to avoid doing a separate query just to get the venue details in the serializer. So all in all:

menu_item_search = VenueMenu.objects.filter(
    venue_filter & menu_item_filter,
).select_related(
    'venue',
).prefetch_related(
    Prefetch(
        'menu_item',
        queryset=MenuItem.objects.filter(name__icontains=request.GET.get('search_name'))
    )
)

Leave a comment