sql.py 1.1 KB

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