[Django]-Related Field got invalid lookup: icontains

83👍

You can use icontains lookup on text fields. user is related (integer) field. Instead of user use user__username.

locations = Location.objects.filter(user__username__icontains=q)

0👍

class SearchView(ListView):
model = Profile
template_name = 'blog/search_results.html'
context_object_name = 'all_search_results'
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    user_name = self.request.GET.get('search', '')
    context['all_search_results'] = Profile.objects.filter(user__username__icontains=user_name )
    return context  

here is another example on how to filter objects. if searching for a user, remember to user user_username__icontains=user_name

also remember that if you use Profile your’ll get a different id than if you use User

👤Koops

Leave a comment