1
- from typing import Optional , Set
1
+ from typing import Dict , Optional , Set
2
2
3
3
from pydantic import BaseModel
4
4
@@ -10,3 +10,41 @@ class FieldsExtension(BaseModel):
10
10
11
11
includes : Optional [Set [str ]]
12
12
excludes : Optional [Set [str ]]
13
+
14
+ def _get_field_dict (self , fields : Set [str ]) -> Dict :
15
+ """Internal method to create a dictionary for advanced include or exclude of pydantic fields on model export
16
+
17
+ Ref: https://pydantic-docs.helpmanual.io/usage/exporting_models/#advanced-include-and-exclude
18
+ """
19
+ field_dict = {}
20
+ for field in fields :
21
+ if "." in field :
22
+ parent , key = field .split ("." )
23
+ if parent not in field_dict :
24
+ field_dict [parent ] = {key }
25
+ else :
26
+ field_dict [parent ].add (key )
27
+ else :
28
+ field_dict [field ] = ... # type:ignore
29
+ return field_dict
30
+
31
+ @property
32
+ def filter (self ) -> Dict :
33
+ """
34
+ Create dictionary of fields to include/exclude on model export based on the included and excluded fields passed
35
+ to the API. The output of this property may be passed to pydantic's serialization methods to include or exclude
36
+ certain keys.
37
+
38
+ Ref: https://pydantic-docs.helpmanual.io/usage/exporting_models/#advanced-include-and-exclude
39
+ """
40
+ include = set ()
41
+ # If only include is specified, add fields to the set
42
+ if self .includes and not self .excludes :
43
+ include = include .union (self .includes )
44
+ # If both include + exclude specified, find the difference between sets
45
+ elif self .includes and self .excludes :
46
+ include = include .union (self .includes ) - self .excludes
47
+ return {
48
+ "include" : self ._get_field_dict (include ),
49
+ "exclude" : self ._get_field_dict (self .excludes ),
50
+ }
0 commit comments