@@ -105,6 +105,41 @@ class Person(BaseModel):
105105 )
106106 assert serializer .fields ["phone_number" ].allow_null is False
107107
108+ def test_regex_from_field (self ):
109+ pattern = r"^\+?[0-9]+$"
110+
111+ class Person (BaseModel ):
112+ phone_number : typing .Annotated [
113+ str ,
114+ pydantic .Field (pattern = pattern ),
115+ ]
116+
117+ serializer = Person .drf_serializer ()
118+
119+ assert isinstance (serializer .fields ["phone_number" ], serializers .RegexField )
120+ assert serializer .fields ["phone_number" ].validators [- 1 ].regex == re .compile (
121+ pattern
122+ )
123+ assert serializer .fields ["phone_number" ].allow_null is False
124+
125+ def test_compiled_regex (self ):
126+ pattern = r"^\+?[0-9]+$"
127+ compiled_pattern = re .compile (pattern )
128+
129+ class Person (BaseModel ):
130+ phone_number : typing .Annotated [
131+ str ,
132+ pydantic .StringConstraints (pattern = compiled_pattern ),
133+ ]
134+
135+ serializer = Person .drf_serializer ()
136+
137+ assert isinstance (serializer .fields ["phone_number" ], serializers .RegexField )
138+ assert serializer .fields ["phone_number" ].validators [- 1 ].regex == re .compile (
139+ pattern
140+ )
141+ assert serializer .fields ["phone_number" ].allow_null is False
142+
108143 def test_optional_regex (self ):
109144 pattern = r"^\+?[0-9]+$"
110145
@@ -137,6 +172,21 @@ class Person(BaseModel):
137172 assert "Error when converting model: Person" in str (exc_info .value )
138173 assert "Field has multiple regex patterns" in str (exc_info .value )
139174
175+ def test_multiple_regex_with_field_error (self ):
176+ with pytest .raises (ModelConversionError ) as exc_info :
177+
178+ class Person (BaseModel ):
179+ phone_number : typing .Annotated [
180+ str ,
181+ pydantic .StringConstraints (pattern = r"123" ),
182+ pydantic .Field (pattern = r"456" ),
183+ ]
184+
185+ Person .drf_serializer ()
186+
187+ assert "Error when converting model: Person" in str (exc_info .value )
188+ assert "Field has multiple regex patterns" in str (exc_info .value )
189+
140190 def test_url (self ):
141191 class Person (BaseModel ):
142192 website : pydantic .HttpUrl
0 commit comments