Giranyx Pornasdoro
Giranyx Pornasdoro

Reputation: 135

Django - how to add another field to be search in my queryset

Currently studying django. I'm trying to add genre icontains for my existing search which only fetch title. but i wonder why i'm getting error of Related Field got invalid lookup: icontains

this is my search code in views.py

def Search(request):
    queryset = Book.objects.all()
    query = request.GET.get('q')
    if query:
        queryset = queryset.filter(
            Q(title__icontains=query) |
            Q(genre__icontains=query) 
        ).distinct()
    context = {
        'queryset': queryset
    }
    return render(request, 'search_results.html', context)

here is my book model.

class Book(models.Model):

  title = models.CharField(max_length=200)
  ```some fields```
  genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")



 def __str__(self):
     return self.title

 def get_absolute_url(self):
     return reverse('book-detail', kwargs={'slug': self.slug})

here's my genre models

class Genre(models.Model):
name = models.CharField(
    max_length=200,
    help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)"
)
featured = models.BooleanField(null=True, default=False)

def __str__(self):
    return self.name

Traceback:

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\thesis\blackink_website\catalog\views.py" in Search 73. Q(genre__icontains=query)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in filter 844. return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 862. clone.query.add_q(Q(*args, **kwargs))

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in add_q 1263. clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in _add_q 1281. current_negated, allow_joins, split_subq)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in _add_q 1287. split_subq=split_subq,

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in build_filter 1225. condition = self.build_lookup(lookups, col, value)

File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in build_lookup 1087. raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))

Exception Type: FieldError at /search/ Exception Value: Related Field got invalid lookup: icontains

Upvotes: 1

Views: 292

Answers (1)

Ngoc Pham
Ngoc Pham

Reputation: 1450

Because genre is ManyToMany. If you use icontain, you must lookup one field of Genre. Like example with field id: Q(genre__id__icontains=query)

With your updated. I guess you want find name of genre. You can try update querylike this:

    queryset = queryset.filter(
        Q(title__icontains=query) |
        Q(genre__name __icontains=query) 
    ).distinct()

Upvotes: 2

Related Questions