queries.txt 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. =====================
  2. Query-related classes
  3. =====================
  4. .. currentmodule:: django.db.models
  5. This document provides reference material for query-related tools not
  6. documented elsewhere.
  7. ``Q()`` objects
  8. ===============
  9. .. class:: Q
  10. A ``Q()`` object, like an :class:`~django.db.models.F` object, encapsulates a
  11. SQL expression in a Python object that can be used in database-related
  12. operations.
  13. In general, ``Q() objects`` make it possible to define and reuse conditions.
  14. This permits the :ref:`construction of complex database queries
  15. <complex-lookups-with-q>` using ``|`` (``OR``) and ``&`` (``AND``) operators;
  16. in particular, it is not otherwise possible to use ``OR`` in ``QuerySets``.
  17. ``Prefetch()`` objects
  18. ======================
  19. .. versionadded:: 1.7
  20. .. class:: Prefetch(lookup, queryset=None, to_attr=None)
  21. The ``Prefetch()`` object can be used to control the operation of
  22. :meth:`~django.db.models.query.QuerySet.prefetch_related()`.
  23. The ``lookup`` argument describes the relations to follow and works the same
  24. as the string based lookups passed to
  25. :meth:`~django.db.models.query.QuerySet.prefetch_related()`.
  26. The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup.
  27. This is useful to further filter down the prefetch operation, or to call
  28. :meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched
  29. relation, hence reducing the number of queries even further.
  30. The ``to_attr`` argument sets the result of the prefetch operation to a custom
  31. attribute.
  32. .. note::
  33. When using ``to_attr`` the prefetched result is stored in a list.
  34. This can provide a significant speed improvement over traditional
  35. ``prefetch_related`` calls which store the cached result within a
  36. ``QuerySet`` instance.