Advertisement
Guest User

Untitled

a guest
Nov 24th, 2015
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. from django.db import models
  2. from django.db.models.query import QuerySet
  3.  
  4.  
  5. class QuerySetExplainMixin:
  6. """Dump SQL EXPLAIN for a Queryset."""
  7. def explain(self, analyze=False, verbose=False):
  8. from django.db import connections
  9. cursor = connections[self.db].cursor()
  10. cmd = 'explain'
  11. cmd += ' analyze' if analyze else ''
  12. cmd += ' verbose' if verbose else ''
  13. cursor.execute('%s %s' % (cmd, str(self.query)))
  14. return cursor.fetchall()
  15.  
  16.  
  17. class QuerySetFieldValuesMixin:
  18. """Returns generator of values for one field on a Queryset."""
  19. def field_values(self, field_name, distinct=False):
  20. values = self.values(field_name)
  21. if distinct:
  22. values = values.distinct()
  23. return (row[field_name] for row in values)
  24.  
  25.  
  26. class QuerySetCountGroupbyMixin:
  27. """
  28. Useful for debugging in shell.
  29.  
  30. Return a COUNT(*) GROUP BY breakdown of queryset by a specified attribute,
  31. i.e. a sorted (descending) list of dictionaries {attr value: count} of each
  32. represented attribute.
  33.  
  34. By default, print human readable breakdown.
  35. """
  36. def count_groupby(self, attr, silent=False):
  37. counts = (self.values(attr).annotate(count=models.Count(attr))
  38. .order_by('count').reverse())
  39.  
  40. choices = dict(getattr(self.model._meta.get_field(attr), 'choices', []))
  41. if not silent and choices.keys():
  42. for group in counts:
  43. print group['count'], '\t', choices.get(group[attr])
  44.  
  45. return counts
  46.  
  47.  
  48. QuerySet.__bases__ += (QuerySetExplainMixin, QuerySetFieldValuesMixin,
  49. QuerySetCountGroupbyMixin)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement