The linked field received an invalid search: icontains

I am trying to include a search box in my homepage. It works for some module field. My problem is that I am using the ForeignKey field (correct me 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 that I use user inside the filter request instead of my_location . I get an error message:

The linked field received an invalid search: icontains

Consult with any troubleshooting tips or documentation I can read.

+5
source share
1 answer

You can use the search icontains in the text fields. user is a related (integer) field. Use user__username instead of user .

 locations = Location.objects.filter(user__username__icontains=q) 
+16
source

Source: https://habr.com/ru/post/1241484/


All Articles