sql.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. from __future__ import unicode_literals
  2. from django.db import connections, models
  3. from django.db.models.sql.compiler import SQLCompiler
  4. class NullsFirstSQLCompiler(SQLCompiler):
  5. def get_order_by(self):
  6. result = super(NullsFirstSQLCompiler, self).get_order_by()
  7. if result:
  8. return [(expr, (sql + ' NULLS FIRST', params, is_ref)) for (expr, (sql, params, is_ref)) in result]
  9. return result
  10. class NullsFirstQuery(models.sql.query.Query):
  11. def get_compiler(self, using=None, connection=None):
  12. if using is None and connection is None:
  13. raise ValueError("Need either using or connection")
  14. if using:
  15. connection = connections[using]
  16. return NullsFirstSQLCompiler(self, connection, using)
  17. class NullsFirstQuerySet(models.QuerySet):
  18. """
  19. Override PostgreSQL's default behavior of ordering NULLs last. This is needed e.g. to order Prefixes in the global
  20. table before those assigned to a VRF.
  21. """
  22. def __init__(self, model=None, query=None, using=None, hints=None):
  23. super(NullsFirstQuerySet, self).__init__(model, query, using, hints)
  24. self.query = query or NullsFirstQuery(self.model)