5
5
from django .conf import settings
6
6
from django .db .backends .base .operations import BaseDatabaseOperations
7
7
from django .utils import timezone
8
+ from django .utils .regex_helper import _lazy_re_compile
8
9
9
10
10
11
class DatabaseOperations (BaseDatabaseOperations ):
11
12
compiler_module = "django_mongodb.compiler"
12
13
14
+ def adapt_datefield_value (self , value ):
15
+ """
16
+ Transform a date value to an object compatible with what is expected
17
+ by the backend driver for date columns.
18
+ """
19
+ if value is None :
20
+ return None
21
+ return datetime .datetime .combine (value , datetime .datetime .min .time ())
22
+
13
23
def adapt_datetimefield_value (self , value ):
14
24
if value is None :
15
25
return None
@@ -30,6 +40,29 @@ def adapt_timefield_value(self, value):
30
40
raise ValueError ("MongoDB backend does not support timezone-aware times." )
31
41
return str (value )
32
42
43
+ # EXTRACT format cannot be passed in parameters.
44
+ _extract_format_re = _lazy_re_compile (r"[A-Z_]+" )
45
+
46
+ def date_extract_sql (self , lookup_type , sql , params ):
47
+ if lookup_type == "week_day" :
48
+ # For consistency across backends, we return Sunday=1, Saturday=7.
49
+ return f"EXTRACT(DOW FROM { sql } ) + 1" , params
50
+ elif lookup_type == "iso_week_day" :
51
+ return f"EXTRACT(ISODOW FROM { sql } )" , params
52
+ elif lookup_type == "iso_year" :
53
+ return f"EXTRACT(ISOYEAR FROM { sql } )" , params
54
+
55
+ lookup_type = lookup_type .upper ()
56
+ if not self ._extract_format_re .fullmatch (lookup_type ):
57
+ raise ValueError (f"Invalid lookup type: { lookup_type !r} " )
58
+ return f"EXTRACT({ lookup_type } FROM { sql } )" , params
59
+
60
+ def datetime_extract_sql (self , lookup_type , sql , params , tzname ):
61
+ if lookup_type == "second" :
62
+ # Truncate fractional seconds.
63
+ return f"EXTRACT(SECOND FROM DATE_TRUNC(%s, { sql } ))" , ("second" , * params )
64
+ return self .date_extract_sql (lookup_type , sql , params )
65
+
33
66
def datetime_trunc_sql (self , lookup_type , sql , params , tzname ):
34
67
return f"DATE_TRUNC(%s, { sql } )" , (lookup_type , * params )
35
68
@@ -54,7 +87,7 @@ def get_db_converters(self, expression):
54
87
55
88
def convert_datefield_value (self , value , expression , connection ):
56
89
if value is not None :
57
- value = datetime .date . fromisoformat ( value )
90
+ value = value .date ( )
58
91
return value
59
92
60
93
def convert_datetimefield_value (self , value , expression , connection ):
0 commit comments