Reputation: 1456
I'm using TinyDB in my python project. However, in order to make the logic effective, I need to be able to get multiple objects in a query. My preference would be to use a list
listOfIDs = ['123', '456']
I am using the latest Python version and TinyDB implementation.
I have the following implementation:
from tinydb import TinyDB, Query
db = TinyDB('db.json')
myDBQuery= Query()
db.insert({'id': '123', 'name': 'bob'})
db.insert({'id': '456', 'name': 'mary'})
result = db.search(myDBQuery.id.all(['123', '456']))
print(result)
However, I keep getting the following as a result:
[]
I know my implementation is working because when I do the following, I get the expected results:
result = db.search((myDBQuery.id == '123') | myDBQuery.id == '456'))
Anyone know how to query with a list in TinyDB?
Anyone know how to query with a list in TinyDB?
EDIT
For those of you wondering, there isn't a way to do it with the current implementation. My only workaround is to create something like the following
def getAllObjectsMatchingId(listOfIds):
tempList = []
for idMember in tempList:
result = db.search(myDBQuery.id == idMember)
tempList.append(result)
return tempList
Upvotes: 3
Views: 7616
Reputation: 964
If anyone still comes accross with this, an alternative to Reinaldo's implementation:
listOfIds = ['1','2','3']
q = Query()
db.search(q.id.one_of(listOfIds))
Taken from Query's API:
one_of(items: List[Any]) → tinydb.queries.QueryInstance
Check if the value is contained in a list or generator.
You can also negate the query (which was what I needed) to get the items that are NOT in the list:
listOfIds = ['4','5']
q = Query()
db.search(~q.id.one_of(listOfIds))
Upvotes: 1
Reputation: 193
This seems the best solution to me:
db.search(myDBQuery.id.test(lambda x: x in listOfIDs))
test() Matches any document for which the function returns True
Upvotes: 0
Reputation: 1932
.all
returns true only if all the elements of the list match the query
.any
might work instead
result = db.search(myDBQuery.id.any(['123', '456']))
EDIT FROM QUESTION OP: Please see my edit above
Upvotes: 4