I'm trying to create a Django filter using a variable as filter input for a contains query on a jsonfield. I just cannot get it to work. Form what I'm finding the solution should be using kwargs but I'm lost how to implement this.
lookupValue = "[{{\"displayName\":\"{0}\"}}]".format(user['name'])
print("value is: ")
print(lookupValue)
recent_user_calls = CallRecord.objects.filter(participants__contains = [{"displayName":"Some Name"}])
#recent_user_calls = CallRecord.objects.filter(participants__contains = lookupValue)
I create the value I want to search and put it in lookup value. In the last commented out line I try to use this value in de query. This does not work as where the previous line works perfectly. A few lines before I print the lookupvalue and it is 100% the same as the fully typed out version. I'm have been staring at this for 2 days. Can someone please point me in the right direction?
CodePudding user response:
The problem is that the variable you are passing in the query is a string and not a list.
You can write:
recent_user_calls = CallRecord.objects.filter(participants__contains = [{"displayName":user['name']}])
Or you can directly filter using the key:
recent_user_calls = CallRecord.objects.filter(participants__displayName=user['name'])