Skip to content

Commit

Permalink
pre-generate initial pypika query object per model, as it is immutable
Browse files Browse the repository at this point in the history
  • Loading branch information
grigi committed Oct 14, 2018
1 parent dbf7646 commit 235554f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
8 changes: 8 additions & 0 deletions tortoise/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,12 @@ def _get_config_from_config_file(cls, config_file):
)
return config

@classmethod
def _build_initial_querysets(cls):
for app_name, app in cls.apps.items():
for model_name, model in app.items():
model._meta.basequery = model._meta.db.query_class.from_(model._meta.table)

@classmethod
async def init(
cls,
Expand Down Expand Up @@ -303,6 +309,8 @@ async def init(

cls._init_relations()

cls._build_initial_querysets()

cls._inited = True

@classmethod
Expand Down
4 changes: 3 additions & 1 deletion tortoise/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,8 @@ def get_filters_for_field(field_name: str, field: Optional[fields.Field], source
class MetaInfo:
__slots__ = ('abstract', 'table', 'app', 'fields', 'db_fields', 'm2m_fields', 'fk_fields',
'backward_fk_fields', 'fetch_fields', 'fields_db_projection', '_inited',
'fields_db_projection_reverse', 'filters', 'fields_map', 'default_connection')
'fields_db_projection_reverse', 'filters', 'fields_map', 'default_connection',
'basequery')

def __init__(self, meta):
self.abstract = getattr(meta, 'abstract', False) # type: bool
Expand All @@ -236,6 +237,7 @@ def __init__(self, meta):
self.fields_map = {} # type: Dict[str, fields.Field]
self._inited = False
self.default_connection = None
self.basequery = None

@property
def db(self):
Expand Down
6 changes: 1 addition & 5 deletions tortoise/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,7 @@ def __init__(self, model) -> None:
self.fields = model._meta.db_fields
self.model = model

if not hasattr(model._meta.db, 'query_class'):
# do not build Query if Tortoise wasn't inited
self.query = None
else:
self.query = model._meta.db.query_class.from_(model._meta.table)
self.query = model._meta.basequery

self._prefetch_map = {} # type: Dict[str, Set[str]]
self._prefetch_queries = {} # type: Dict[str, QuerySet]
Expand Down

0 comments on commit 235554f

Please sign in to comment.