Related Field got invalid lookup: icontains

Question:

I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong).

models.py

class Location(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    update_date = models.DateField(auto_now=True, null=True)

    def __str__(self):
        return self.my_location


class UserProfile(models.Model):

    user = models.ForeignKey(User)
    # The additional attributes we wish to include.
    user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    user_position = models.CharField(max_length=120)
    user_phone = models.PositiveIntegerField()

    def __unicode__(self):
        return self.user.username

views.py

def search_by_location(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        locations = Location.objects.filter(my_location__icontains=q).order_by('-update_date')
    else:
        locations = Location.objects.order_by('-update_date')
context = {'locations': locations}
return render(request, 'index.html', context)

My problem is if I use user inside the filter query instead of my_location I receive the error:

Related Field got invalid lookup: icontains

Please any advice on how to troubleshoot or any documentation I can read.

Asked By: marwan h-sleiman

||

Answers:

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)
Answered By: Tomasz Jakub Rup
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

Answered By: Leandro Cooper
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.