Opened 6 years ago

Closed 6 years ago

#12021 closed (duplicate)

.any() method on QuerySet using a known trick

Reported by: Vlada Macek Owned by: nobody
Component: Database layer (models, ORM) Version:
Severity: Keywords:
Cc: t.django@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

While inspecting the Django code, I found this trick:

# This cute trick with extra/values is the most efficient way to   
# tell if a particular query returns any results.                  
if qs.extra(select={'a': 1}).values('a').order_by():

It apparently turns off the ordering as well as retrieving and parsing any real value from the db, resulting in something very cheap like:

SELECT (1) AS "a" FROM <table> WHERE <previous-qs-filtering>

Which is what we wanted to get the any/none info.

I think many of us frequently need this, but build unnecessarily complex constructs, while this can easily make it to a new QuerySet method called, say, .any().

Change History (2)

comment:1 Changed 6 years ago by anonymous

  • Cc t.django@… added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 6 years ago by russellm

  • Resolution set to duplicate
  • Status changed from new to closed

Duplicate of #11402

Note: See TracTickets for help on using tickets.
Back to Top