From f80a6448f7cd3835beb6ac90fced5da7d9d3f654 Mon Sep 17 00:00:00 2001 From: MohammadMahdi Khalaj Date: Mon, 13 Nov 2023 12:39:32 +0330 Subject: [PATCH] Make copy of created field in lookup --- aggify/aggify.py | 7 +++---- aggify/utilty.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/aggify/aggify.py b/aggify/aggify.py index a2e3b1c..e208889 100644 --- a/aggify/aggify.py +++ b/aggify/aggify.py @@ -22,6 +22,7 @@ convert_match_query, check_field_already_exists, get_db_field, + copy_class, ) AggifyType = TypeVar("AggifyType", bound=Callable[..., "Aggify"]) @@ -56,9 +57,7 @@ def __init__(self, base_model: Type[Document]): base_model: The base model class. """ # Create a separate copy of the main class for safety and flexibility - self.base_model = type( - "Aggify_base_model", base_model.__bases__, dict(base_model.__dict__) - ) + self.base_model = copy_class(base_model) self.pipelines: List[Dict[str, Union[dict, Any]]] = [] self.start = None self.stop = None @@ -656,7 +655,7 @@ def lookup( self.pipelines.append(lookup_stage) # Add this new field to base model fields, which we can use it in the next stages. - self.base_model._fields[as_name] = from_collection # noqa + self.base_model._fields[as_name] = copy_class(from_collection) # noqa return self diff --git a/aggify/utilty.py b/aggify/utilty.py index 70d9a35..eacd7c9 100644 --- a/aggify/utilty.py +++ b/aggify/utilty.py @@ -168,3 +168,22 @@ def get_nested_field_model(model: CollectionType, field: str) -> CollectionType: if model._fields[field].__dict__.get("__module__"): # noqa return model return model._fields[field].__dict__["document_type_obj"] # noqa + + +def copy_class(original_class): + """ + Copies a class, creating a new class with the same bases and attributes. + + Parameters: + original_class (class): The class to be copied. + + Returns: + class: A new class with the same bases and attributes as the original class. + """ + # Create a new class with the same name, bases, and attributes + copied_class = type( + "Aggify" + original_class.__name__, + original_class.__bases__, + dict(original_class.__dict__), + ) + return copied_class