-
-
Notifications
You must be signed in to change notification settings - Fork 129
Closed
Description
hi 👋
in web development it is common to ask for a list of values
for example if we have a database table called human, sometimes we want to see data about a single human, sometimes we want to see a bunch of data in one place
i have achived this goal using cattrs, but I'm wondering if my way can be improved
my code so far:
data classes:
type DataList = list
@define
class HumanDataModel:
name: str
@define
class HumanDataModelList:
data: Annotated[DataList, HumanDataModel]
def __iter__(self): # needed to unstructure as a list
return iter(self.data)hooks:
def data_list_structure(val, t):
annotation = get_args(t)
data_model: type = annotation[1]
return [converter.structure(v, data_model) for v in val]
def data_list_structure_serializer(val, t):
annotation = get_args(t)
data_model: type = annotation[1]
return [converter.structure(v, data_model) for v in val]
def data_list_unstructure(val):
return [converter.unstructure(v) for v in val]
converter.register_structure_hook_func(
lambda t: is_annotated(t) and get_args(t)[0] is DataList, data_list_structure
)
converter.register_unstructure_hook(DataList, data_list_unstructure)and it's used like this:
data = Human.objects.all() # ORM call
structure = converter.structure({"data": data}, HumanDataModelList)
unstructure = converter.unstructure(structure, list) # has to be unstructured as a listthe main thing that bugs me is that i have to create a secone list class for each data class i have, so i was wondering if there is a built-in way of handling this that i am missing
i can probably generate the second class dynamically, but thought it's worth checking in before goin on that route
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels