1

I should be able to use the queryset '_contains' on my Django object variables to filter my results, according to this documentation

But when I implement this code:

cookbooks = Books.objects.filter (category_contains = 'cooking')

I get the following error:

Cannot resolve keyword 'category_contains' into field. Choices are: category, adder, date etc.

Why is this happening? I also saw this StackOverflow question where someone explains that just using variable category implies category_exact. But if I write category_exact I get a similar error.

Community
  • 1
  • 1
user1328021
  • 9,110
  • 14
  • 47
  • 78

2 Answers2

5

You need to use a double underscore __ not a single underscore _.

Marcin
  • 48,559
  • 18
  • 128
  • 201
3

Field lookups are prefixed via two underscores (__) not one (_). It can be hard to tell the difference at first when you are not familiar with the syntax.

Double check the documentation for field lookups in general and more specifically the contains documentation. Here is the example from the contains documentation with comments showing one or two underscores:

Entry.objects.get(headline__contains='Lennon')
#                         __ <-- 2 _'s
#                     not _  <-- 1 _
istruble
  • 13,363
  • 2
  • 47
  • 52
  • The solution for me was your `=`. Note, that Django gives `NameError` on `Entry.objects.get(headline__contains('Lennon'))`, telling that the `headline__contains` name is not defined. But **change parentheses to =** and the NamError goes away. – Morten Engelsmann Nov 15 '20 at 18:35