diff --git a/django_mongodb/compiler.py b/django_mongodb/compiler.py index 56a4c9903..a8fba8a8e 100644 --- a/django_mongodb/compiler.py +++ b/django_mongodb/compiler.py @@ -409,7 +409,8 @@ def project_field(column): def collection_name(self): return self.query.get_meta().db_table - def get_collection(self): + @cached_property + def collection(self): return self.connection.get_collection(self.collection_name) def get_lookup_pipeline(self): @@ -516,8 +517,7 @@ def execute_sql(self, returning_fields=None): @wrap_database_errors def insert(self, docs, returning_fields=None): """Store a list of documents using field columns as element names.""" - collection = self.get_collection() - inserted_ids = collection.insert_many(docs).inserted_ids + inserted_ids = self.collection.insert_many(docs).inserted_ids return inserted_ids if returning_fields else [] @@ -582,12 +582,11 @@ def update(self, values): @wrap_database_errors def execute_update(self, update_spec): - collection = self.get_collection() try: criteria = self.build_query().mongo_query except EmptyResultSet: return 0 - return collection.update_many(criteria, update_spec).matched_count + return self.collection.update_many(criteria, update_spec).matched_count def check_query(self): super().check_query() diff --git a/django_mongodb/query.py b/django_mongodb/query.py index db2b8adcf..a2ac7cc3e 100644 --- a/django_mongodb/query.py +++ b/django_mongodb/query.py @@ -43,7 +43,7 @@ def __init__(self, compiler): self.query = compiler.query self._negated = False self.ordering = [] - self.collection = self.compiler.get_collection() + self.collection = self.compiler.collection self.collection_name = self.compiler.collection_name self.mongo_query = getattr(compiler.query, "raw_query", {}) self.subquery = None