Created on Nov. 19, 2012, 10:48 a.m. by Hevok & updated on Nov. 19, 2012, 10:48 a.m. by Hevok
A queryset has query property that allows to see the associated sql statement.
¶
¶
For instance to query the ORM to find recently active users - users who joined the last month or who have logged in this month:
¶
¶
.. sourcecode:: python
¶
¶
>>> from datetime import date
¶
>>> from django.contrib.auth.models import User
¶
>>> from django.db.models import Q
¶
>>> nov_1st = date(2012, 11, 1)
¶
>>> recent = User.objects.filter(Q(last_login_gte=nov_1st)
¶
| Q(date_joined__gte=nov_1st))
¶
>>> print(recent.query)
¶
¶
The bit-wise OR operator can also be applied on QuerySets:
¶
¶
.. sourcecode:: python
¶
¶
>>> from datetime import date
¶
>>> from django.contrib.auth.models import User
¶
>>> nov_1st = date(2012, 11, 1)
¶
>>> recent_login = User.objects.filter(last_login__gte=nov_1st)
¶
>>> recent_join = User.objects.filter(date_joined__gte=nov_1st)
¶
>>> recent = recent_login | recent_join
¶
>>> print(recent.query)
¶
¶
However note that the Q object might be more efficient as it can prevent for example duplications in the where clausal.
¶
Comment on This Data Unit