Skip to content

Instantly share code, notes, and snippets.

@dchaplinsky
Created November 16, 2010 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dchaplinsky/701757 to your computer and use it in GitHub Desktop.
Save dchaplinsky/701757 to your computer and use it in GitHub Desktop.
Method to avoid heavy filesort
class FoobarManager(models.Manager):
def latest(self, limit=10):
""" more effecient version of query to avoid filesort """
ids = list(self.values_list('id', flat=True).order_by('-created')[:limit])
return self.filter(id__in=ids).extra(
select={'manual': 'FIELD(id,%s)' % ','.join(map(str, ids))},
order_by=['manual'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment