11from __future__ import annotations
22
3- import sys
43import warnings
54from collections .abc import AsyncGenerator , Generator , Iterator
65from typing import TYPE_CHECKING , Any , Generic , Literal , TypeVar , overload
1716 RelationalFieldKwargs ,
1817)
1918
20- if sys .version_info >= (3 , 11 ):
21- from typing import Unpack
22- else : # pragma: no cover
23- from typing_extensions import Unpack
24-
2519if TYPE_CHECKING : # pragma: nocoverage
20+ import sys
21+
2622 from tortoise .backends .base .client import BaseDBAsyncClient
2723 from tortoise .models import Model
2824 from tortoise .queryset import Q , QuerySet
2925
26+ if sys .version_info >= (3 , 11 ):
27+ from typing import Unpack
28+ else : # pragma: no cover
29+ from typing_extensions import Unpack
30+
3031MODEL = TypeVar ("MODEL" , bound = "Model" )
3132
3233
@@ -132,7 +133,9 @@ def offset(self, offset: int) -> QuerySet[MODEL]:
132133 """
133134 return self ._query .offset (offset )
134135
135- async def create (self , using_db : BaseDBAsyncClient | None = None , ** kwargs : Any ) -> MODEL :
136+ async def create (
137+ self , using_db : BaseDBAsyncClient | None = None , ** kwargs : Any
138+ ) -> MODEL :
136139 """
137140 Create a related record in the DB and returns the object, automatically setting the
138141 foreign key relationship to the parent instance.
@@ -164,7 +167,9 @@ async def create(self, using_db: BaseDBAsyncClient | None = None, **kwargs: Any)
164167 # Call remote model's create method
165168 return await self .remote_model .create (using_db = using_db , ** kwargs )
166169
167- def _set_result_for_query (self , sequence : list [MODEL ], attr : str | None = None ) -> None :
170+ def _set_result_for_query (
171+ self , sequence : list [MODEL ], attr : str | None = None
172+ ) -> None :
168173 self ._fetched = True
169174 self .related_objects = sequence
170175 if attr :
@@ -182,12 +187,18 @@ class ManyToManyRelation(ReverseRelation[MODEL]):
182187 Many-to-many relation container for :func:`.ManyToManyField`.
183188 """
184189
185- def __init__ (self , instance : Model , m2m_field : ManyToManyFieldInstance [MODEL ]) -> None :
186- super ().__init__ (m2m_field .related_model , m2m_field .related_name , instance , "pk" )
190+ def __init__ (
191+ self , instance : Model , m2m_field : ManyToManyFieldInstance [MODEL ]
192+ ) -> None :
193+ super ().__init__ (
194+ m2m_field .related_model , m2m_field .related_name , instance , "pk"
195+ )
187196 self .field = m2m_field
188197 self .instance = instance
189198
190- async def add (self , * instances : MODEL , using_db : BaseDBAsyncClient | None = None ) -> None :
199+ async def add (
200+ self , * instances : MODEL , using_db : BaseDBAsyncClient | None = None
201+ ) -> None :
191202 """
192203 Adds one or more of ``instances`` to the relation.
193204
@@ -206,16 +217,25 @@ async def add(self, *instances: MODEL, using_db: BaseDBAsyncClient | None = None
206217 pks_f : list = []
207218 for instance_to_add in instances :
208219 if not instance_to_add ._saved_in_db :
209- raise OperationalError (f"You should first call .save() on { instance_to_add } " )
220+ raise OperationalError (
221+ f"You should first call .save() on { instance_to_add } "
222+ )
210223 pk_f = related_pk_formatting_func (instance_to_add .pk , instance_to_add )
211224 pks_f .append (pk_f )
212225 through_table = Table (self .field .through , schema = self .field .through_schema )
213226 backward_key , forward_key = self .field .backward_key , self .field .forward_key
214- backward_field , forward_field = through_table [backward_key ], through_table [forward_key ]
227+ backward_field , forward_field = (
228+ through_table [backward_key ],
229+ through_table [forward_key ],
230+ )
215231 select_query = (
216- db .query_class .from_ (through_table ).where (backward_field == pk_b ).select (forward_key )
232+ db .query_class .from_ (through_table )
233+ .where (backward_field == pk_b )
234+ .select (forward_key )
235+ )
236+ criterion = (
237+ forward_field == pks_f [0 ] if len (pks_f ) == 1 else forward_field .isin (pks_f )
217238 )
218- criterion = forward_field == pks_f [0 ] if len (pks_f ) == 1 else forward_field .isin (pks_f )
219239 select_query = select_query .where (criterion )
220240
221241 _ , already_existing_relations_raw = await db .execute_query (
@@ -227,7 +247,9 @@ async def add(self, *instances: MODEL, using_db: BaseDBAsyncClient | None = None
227247 }
228248
229249 if pks_f_to_insert := set (pks_f ) - already_existing_forward_pks :
230- query = db .query_class .into (through_table ).columns (forward_field , backward_field )
250+ query = db .query_class .into (through_table ).columns (
251+ forward_field , backward_field
252+ )
231253 for pk_f in pks_f_to_insert :
232254 query = query .insert (pk_f , pk_b )
233255 await db .execute_query (* query .get_parameterized_sql ())
@@ -238,7 +260,9 @@ async def clear(self, using_db: BaseDBAsyncClient | None = None) -> None:
238260 """
239261 await self ._remove_or_clear (using_db = using_db )
240262
241- async def remove (self , * instances : MODEL , using_db : BaseDBAsyncClient | None = None ) -> None :
263+ async def remove (
264+ self , * instances : MODEL , using_db : BaseDBAsyncClient | None = None
265+ ) -> None :
242266 """
243267 Removes one or more of ``instances`` from the relation.
244268
@@ -263,9 +287,9 @@ async def _remove_or_clear(
263287 if instances :
264288 related_pk_formatting_func = type (instances [0 ])._meta .pk .to_db_value
265289 if len (instances ) == 1 :
266- condition &= through_table [self . field . forward_key ] == related_pk_formatting_func (
267- instances [ 0 ]. pk , instances [ 0 ]
268- )
290+ condition &= through_table [
291+ self . field . forward_key
292+ ] == related_pk_formatting_func ( instances [ 0 ]. pk , instances [ 0 ] )
269293 else :
270294 condition &= through_table [self .field .forward_key ].isin (
271295 [related_pk_formatting_func (i .pk , i ) for i in instances ]
@@ -293,7 +317,9 @@ def __init__(
293317 if TYPE_CHECKING :
294318
295319 @overload
296- def __get__ (self , instance : None , owner : type [Model ]) -> RelationalField [MODEL ]: ...
320+ def __get__ (
321+ self , instance : None , owner : type [Model ]
322+ ) -> RelationalField [MODEL ]: ...
297323
298324 @overload
299325 def __get__ (self , instance : Model , owner : type [Model ]) -> MODEL : ...
@@ -322,7 +348,9 @@ def validate_model_name(cls, model_name: str | type[Model]) -> None:
322348 ) from None
323349 elif len (model_name .split ("." )) != 2 :
324350 field_type = cls .__name__ .replace ("Instance" , "" )
325- raise ConfigurationError (f'{ field_type } accepts model name in format "app.Model"' )
351+ raise ConfigurationError (
352+ f'{ field_type } accepts model name in format "app.Model"'
353+ )
326354
327355
328356class ForeignKeyFieldInstance (RelationalField [MODEL ]):
@@ -342,7 +370,9 @@ def __init__(
342370 "on_delete can only be CASCADE, RESTRICT, SET_NULL, SET_DEFAULT or NO_ACTION"
343371 )
344372 if on_delete == SET_NULL and not bool (kwargs .get ("null" )):
345- raise ConfigurationError ("If on_delete is SET_NULL, then field must have null=True set" )
373+ raise ConfigurationError (
374+ "If on_delete is SET_NULL, then field must have null=True set"
375+ )
346376 self .on_delete = on_delete
347377
348378 def describe (self , serializable : bool ) -> dict :
0 commit comments