How to convert string to django.db.models.query_utils.Q format?

1.8k Views Asked by At

For a search function I want to save django query to database & later execute it. I have saved the query as shown below in one table(Company, which have id,qryText). The django query is saved as string.

qrySaved = (AND: ('code__in', ['10', '11', '12']), ('color__in', ['1', '2', '3']))

I am unable to execute it like

q = Company.objects.get(id=1)
Car.objects.filter(q.qryText)

as q.qryText is a string not django.db.models.query_utils.Q format. How could I execute this string query ?

1

There are 1 best solutions below

2
Wolph On BEST ANSWER

The string representation of the query is not easily (safely) reversible so I would try a different type of encoding instead. For example, using the pickle library instead.

To encode:

import pickle
from django.db.models import query_utils

q = Q(code__in=[10, 11, 12], color_in=[1, 2, 3])
q_pickled = pickle.dumps(q)

To decode again:

# Assuming that q_pickled is available and is a valid pickled string
import pickle

q = pickle.loads(q_pickled)