0

I have a table called Demo which consits of two fields i.e;

Name,hobbies. hobbies contains comma seperated values in db.

for example: "eating,sleeping,dancing"

now i have to query for the field hobbies which contains "eating,sleeping".

I have tried

Demo.object.get(hobbies__in=['eating','sleeping'])

I am getting

matching query does not exists

How can i solve this

praveen jp
  • 197
  • 2
  • 14
  • This is not how the IN operator works in SQL – OptimusCrime Sep 19 '17 at 10:32
  • Did you try to google the error? It happens because you use `get` and there are no such objects in your database. You should use `filter` if you do not know for a fact that the object exists. Additionally, the query is incorrect. – OptimusCrime Sep 19 '17 at 10:39
  • show your deom models please, can you use [commaseparatedintegerfield](https://docs.djangoproject.com/en/1.11/ref/models/fields/#commaseparatedintegerfield) – Brown Bear Sep 19 '17 at 10:39

1 Answers1

0

Unless you can guarantee the order of the two values, then you have to use contains. This translates to LIKE '%eating%' and LIKE '%sleeping%'.

Example:

demos = Demo.object.filter(hobbies__contains='eating', hobbies__contains='sleeping')
OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
  • can we make it dynamic? – praveen jp Sep 19 '17 at 10:47
  • Sure, you can also do `hobbies__contains=my_variable`. You can also see a simple example here: https://stackoverflow.com/a/13076894/921563 If you have problems with it I advice you to Google the problem and if you are not able to solve it, then open a new question. – OptimusCrime Sep 19 '17 at 10:49