Skip to content

Commit c27064c

Browse files
committed
Replace DatabaseWrapper.__getattr__() with a simpler database attribute
1 parent 961ec66 commit c27064c

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

django_mongodb_backend/base.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from django.core.exceptions import ImproperlyConfigured
55
from django.db.backends.base.base import BaseDatabaseWrapper
66
from django.utils.asyncio import async_unsafe
7+
from django.utils.functional import cached_property
78
from pymongo.collection import Collection
89
from pymongo.driver_info import DriverInfo
910
from pymongo.mongo_client import MongoClient
@@ -149,13 +150,13 @@ def get_database(self):
149150
return OperationDebugWrapper(self)
150151
return self.database
151152

152-
def __getattr__(self, attr):
153-
"""Connect to the database the first time `database` is accessed."""
154-
if attr == "database":
155-
if self.connection is None:
156-
self.connect()
157-
return getattr(self, attr)
158-
raise AttributeError(attr)
153+
@cached_property
154+
def database(self):
155+
"""Connect to the database the first time it's accessed."""
156+
if self.connection is None:
157+
self.connect()
158+
# Cache the database attribute set by init_connection_state()
159+
return self.database
159160

160161
def init_connection_state(self):
161162
self.database = self.connection[self.settings_dict["NAME"]]

0 commit comments

Comments
 (0)