11import  json 
22
3- from  django .contrib .postgres .validators  import  ArrayMaxLengthValidator 
43from  django .core  import  checks , exceptions 
54from  django .db .models  import  DecimalField , Field , Func , IntegerField , Transform , Value 
65from  django .db .models .fields .mixins  import  CheckFieldDefaultMixin 
109from  ..forms  import  SimpleArrayField 
1110from  ..query_utils  import  process_lhs , process_rhs 
1211from  ..utils  import  prefix_validation_error 
12+ from  ..validators  import  ArrayMaxLengthValidator , LengthValidator 
1313
1414__all__  =  ["ArrayField" ]
1515
@@ -27,14 +27,20 @@ class ArrayField(CheckFieldDefaultMixin, Field):
2727 }
2828 _default_hint  =  ("list" , "[]" )
2929
30-  def  __init__ (self , base_field , max_size = None , ** kwargs ):
30+  def  __init__ (self , base_field , max_size = None , size = None ,  ** kwargs ):
3131 self .base_field  =  base_field 
3232 self .max_size  =  max_size 
33+  self .size  =  size 
3334 if  self .max_size :
3435 self .default_validators  =  [
3536 * self .default_validators ,
3637 ArrayMaxLengthValidator (self .max_size ),
3738 ]
39+  if  self .size :
40+  self .default_validators  =  [
41+  * self .default_validators ,
42+  LengthValidator (self .size ),
43+  ]
3844 # For performance, only add a from_db_value() method if the base field 
3945 # implements it. 
4046 if  hasattr (self .base_field , "from_db_value" ):
@@ -98,6 +104,14 @@ def check(self, **kwargs):
98104 id = "django_mongodb_backend.array.W004" ,
99105 )
100106 )
107+  if  self .size  and  self .max_size :
108+  errors .append (
109+  checks .Error (
110+  "ArrayField cannot have both size and max_size." ,
111+  obj = self ,
112+  id = "django_mongodb_backend.array.E003" ,
113+  )
114+  )
101115 return  errors 
102116
103117 def  set_attributes_from_name (self , name ):
@@ -127,6 +141,8 @@ def deconstruct(self):
127141 kwargs ["base_field" ] =  self .base_field .clone ()
128142 if  self .max_size  is  not   None :
129143 kwargs ["max_size" ] =  self .max_size 
144+  if  self .size  is  not   None :
145+  kwargs ["size" ] =  self .size 
130146 return  name , path , args , kwargs 
131147
132148 def  to_python (self , value ):
@@ -211,6 +227,7 @@ def formfield(self, **kwargs):
211227 "form_class" : SimpleArrayField ,
212228 "base_field" : self .base_field .formfield (),
213229 "max_length" : self .max_size ,
230+  "length" : self .size ,
214231 ** kwargs ,
215232 }
216233 )
0 commit comments