11from django import VERSION
22from django .db .models import BooleanField
33from django .db .models .functions import Cast
4- from django .db .models .functions .math import ATan2 , Log , Ln , Round
4+ from django .db .models .functions .math import ATan2 , Log , Ln , Mod , Round
55from django .db .models .expressions import Case , Exists , OrderBy , When
66from django .db .models .lookups import Lookup
77
@@ -12,6 +12,34 @@ class TryCast(Cast):
1212 function = 'TRY_CAST'
1313
1414
15+ def sqlserver_as_sql (self , compiler , connection , template = None , ** extra_context ):
16+ template = template or self .template
17+ if connection .features .supports_order_by_nulls_modifier :
18+ if self .nulls_last :
19+ template = '%s NULLS LAST' % template
20+ elif self .nulls_first :
21+ template = '%s NULLS FIRST' % template
22+ else :
23+ if self .nulls_last and not (
24+ self .descending and connection .features .order_by_nulls_first
25+ ) and connection .features .supports_order_by_is_nulls :
26+ template = '%%(expression)s IS NULL, %s' % template
27+ elif self .nulls_first and not (
28+ not self .descending and connection .features .order_by_nulls_first
29+ ) and connection .features .supports_order_by_is_nulls :
30+ template = '%%(expression)s IS NOT NULL, %s' % template
31+ connection .ops .check_expression_support (self )
32+ expression_sql , params = compiler .compile (self .expression )
33+ placeholders = {
34+ 'expression' : expression_sql ,
35+ 'ordering' : 'DESC' if self .descending else 'ASC' ,
36+ ** extra_context ,
37+ }
38+ template = template or self .template
39+ params *= template .count ('%(expression)s' )
40+ return (template % placeholders ).rstrip (), params
41+
42+
1543def sqlserver_atan2 (self , compiler , connection , ** extra_context ):
1644 return self .as_sql (compiler , connection , function = 'ATN2' , ** extra_context )
1745
@@ -26,6 +54,10 @@ def sqlserver_ln(self, compiler, connection, **extra_context):
2654 return self .as_sql (compiler , connection , function = 'LOG' , ** extra_context )
2755
2856
57+ def sqlserver_mod (self , compiler , connection , ** extra_context ):
58+ return self .as_sql (compiler , connection , template = '%(expressions)s' , arg_joiner = '%%' , ** extra_context )
59+
60+
2961def sqlserver_round (self , compiler , connection , ** extra_context ):
3062 return self .as_sql (compiler , connection , template = '%(function)s(%(expressions)s, 0)' , ** extra_context )
3163
@@ -77,6 +109,7 @@ def sqlserver_orderby(self, compiler, connection):
77109ATan2 .as_microsoft = sqlserver_atan2
78110Log .as_microsoft = sqlserver_log
79111Ln .as_microsoft = sqlserver_ln
112+ Mod .as_microsoft = sqlserver_mod
80113Round .as_microsoft = sqlserver_round
81114
82115if DJANGO3 :
@@ -85,3 +118,4 @@ def sqlserver_orderby(self, compiler, connection):
85118 Exists .as_microsoft = sqlserver_exists
86119
87120OrderBy .as_microsoft = sqlserver_orderby
121+ OrderBy .as_sql = sqlserver_as_sql
0 commit comments