You can pass a 2-tuple to a Q
object [Django-doc] with a key and a value:
from django.db.models import Q
MyModel.objects.get(Q((self.myfield, myvar)))
For example, we can generate a query for the .filter(..)
:
>>> print(MyModel.objects.filter(Q(('id', 1))).query)
SELECT `test_mymodel`.`id` FROM `test_mymodel` WHERE `test_mymodel`.`id` = 1
In fact, if you take a look at how Django processes the positional and named parameters of the .get(..)
and .filter(..)
, it makes a Q
object [GitHub]:
…
clone = self._chain()
if negate:
clone.query.add_q(~Q(*args, **kwargs))
else:
clone.query.add_q(Q(*args, **kwargs))
return clone
and the named parameters are converted to (sorted) 2-tuples:
class Q(tree.Node):
# …
def __init__(self, *args, _connector=None, _negated=False, **kwargs):
super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)
so by using a 2-tuple in a Q object, we make a "shortcut" so to speak.