
    W
h(                    H   S SK r S SKrS SKrS SKrS SKJr  S SKrS SKrS SKJ	r	J
r
  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJr  S SKJrJrJrJr  S SK J!r!J"r"J#r#J$r$J%r%  S SK&J'r'J(r(  S SK)J*r*  S SK+J,r,  S SK-J.r.J/r/  Sr0S r1Sr2Sr3Sr4Sr5 " S S5      r6g)    N)Mapping)SON	json_util)Code)ReturnDocument)validate_read_preference)ReadConcern)signals)get_document)_import_class)get_db)!no_dereferencing_active_for_classset_read_write_concernset_write_concern	switch_db)BulkWriteErrorInvalidQueryErrorLookUpErrorNotUniqueErrorOperationError)LEGACY_JSON_OPTIONScount_documents)	transform)QueryFieldList)QQNode)BaseQuerySet
DO_NOTHINGNULLIFYCASCADEDENYPULL            c                      \ rS rSrSrS rSTS jrS rS rS r	S	 r
S
 rS rS rS rSUS jrS rS rS r SVS jrSWS jrSXS jr      SYS jrSZS jr    S[S jr     S\S jrS rS rS rS rS rS rS r S]S  jr!S! r"S" r#STS# jr$STS$ jr%S% r&S& r'S' r(S( r)SWS) jr*S* r+SS+.S, jr,S- r-S. r.S/ r/S0 r0S1 r1S2 r2S3 r3S4 r4S5 r5S6 r6S7 r7S8 r8S9 r9S: r:S; r; S^S< jr<S= r=S> r>S? r?S@ r@S_SA jrASB rBSC rC\DSD 5       rE\DSE 5       rF\DSF 5       rGSG rH\DSH 5       rI\DSI 5       rJ\DSJ 5       rKSK rLSWSL jrMSWSM jrNSN rOSO rPSP rQSQ rRSR rSSSrTg)`r   2   zA set of results returned from a query. Wraps a MongoDB cursor,
providing :class:`~mongoengine.Document` objects as the results.
c                    Xl         X l        S U l        [        5       U l        0 U l        S U l        [        5       U l        S U l	        SU l
        SU l        SU l        S U l        S U l        SU l        / U l        SU l        SU l        S U l        S U l        SU l        SU l        UR.                  R1                  S5      SL ar  [3        U R                   R4                  5      S:X  a!  SU R                   R4                  S   0U l        OSSU R                   R4                  00U l        [        S/S9U l        S U l        S U l        S U l        S	U l        S U l        S U l         S U l!        S U l"        SU l#        g )
NFTallow_inheritancer#   _clsr   $inalways_include)$	_document_collection_obj_mongo_queryr   
_query_obj
_cls_query_where_clauser   _loaded_fields	_ordering	_snapshot_timeout_allow_disk_use_read_preference_read_concern_iter_scalar_none_as_pymongo_search_text_search_text_score_BaseQuerySet__dereference_BaseQuerySet__auto_dereference_metagetlen_subclasses_cursor_obj_limit_skip_hint
_collation_batch_size_max_time_ms_comment_empty)selfdocument
collections      aC:\Users\julio\Documents\inmuebles-mzt\backend\env\Lib\site-packages\mongoengine/queryset/base.py__init__BaseQuerySet.__init__7   s\   !) #!,.$ $!

  "&""& >>12d:4>>--.!3#)4>>+E+Ea+H"I#)E4>>3M3M+N"O"0"ID

      Nc                     [        S0 UD6nU(       a)  [        U[        5      (       d  SU-  n[        U5      eX!-  nU R	                  5       nU=R
                  U-  sl        SUl        SUl        U$ )a  Filter the selected documents by calling the
:class:`~mongoengine.queryset.QuerySet` with a query.

:param q_obj: a :class:`~mongoengine.queryset.Q` object to be used in
    the query; the :class:`~mongoengine.queryset.QuerySet` is filtered
    multiple times with different :class:`~mongoengine.queryset.Q`
    objects, only the last one will be used.
:param query: Django-style query keyword arguments.
z8Not a query object: %s. Did you intend to use key=value?N )r   
isinstancer   r   cloner3   r2   rI   )rR   q_objquerymsgquerysets        rU   __call__BaseQuerySet.__call__i   sv     
E
eU++79>?  (,,NE::<u$ $#rX   c                 f    U R                   R                  5       nUR                  S5        SUS'   U$ )W
Need for pickling queryset

See https://github.com/MongoEngine/mongoengine/issues/442
r1   NrI   )__dict__copypoprR   obj_dicts     rU   __getstate__BaseQuerySet.__getstate__   s6     ==%%' 	&' #'rX   c                 f    US   R                  5       US'   U R                  R                  U5        g)rd   r0   r1   N)_get_collectionre   updaterh   s     rU   __setstate__BaseQuerySet.__setstate__   s1     '/{&;&K&K&M"# 	X&rX   c                    U R                  5       nSUl        [        U[        5      (       a  UR                  U   Ul        UR                  UR                  sUl        Ul	        UR                  (       a/  UR                  (       a  UR                  UR                  -
  Ul	        UR                  S:X  a  SUl        U$ [        U[        5      (       a  UR                  (       a@  UR                  UR                  R                  UR                  U   U R                  S95      $ UR                   (       a  UR                  U   $ UR                  R                  UR                  U   U R                  S9$ [#        S5      e)aK  Return a document instance corresponding to a given index if
the key is an integer. If the key is a slice, translate its
bounds into a skip and a limit, and return a cloned queryset
with that skip/limit applied. For example:

>>> User.objects[0]
<User: User object>
>>> User.objects[1:3]
[<User: User object>, <User: User object>]
Fr   T_auto_dereferencez#Provide a slice or an integer index)r\   rQ   r[   slice_cursorrI   startstoprK   rJ   intr>   _get_scalarr0   	_from_sonrs   r@   	TypeError)rR   keyr`   s      rU   __getitem__BaseQuerySet.__getitem__   sE    ::< c5!!#+#3#3C#8H .1ii+HNHOyySXX"%((SYY"6!#"& O S!!++&&00 ((-*.*@*@ 1   ##'',,%%//  %"&"8"8 0  
 =>>rX   c                     [         eN)NotImplementedErrorrR   s    rU   __iter__BaseQuerySet.__iter__   s    !!rX   c                 L    U R                  5       nUR                  5       c  S$ S$ )z#Return True if cursor has any data.FT)order_byfirstrR   r`   s     rU   	_has_dataBaseQuerySet._has_data   s$    ==? (0u:d:rX   c                 "    U R                  5       $ )z/Avoid to open all records in an if stmt in Py3.)r   r   s    rU   __bool__BaseQuerySet.__bool__   s    ~~rX   c                 "    U R                  5       $ )z'Returns a copy of the current QuerySet.ra   r   s    rU   allBaseQuerySet.all   s    }}rX   c                 &    U R                   " U0 UD6$ )z;An alias of :meth:`~mongoengine.queryset.QuerySet.__call__`r   )rR   q_objsr^   s      rU   filterBaseQuerySet.filter   s    }}f...rX   c                     U R                  5       nUR                  (       a  [        S5      e[        SU05      nU(       a  X%S'   U=R                  [        SU0S9-  sl        SUl        SUl        Xl        X4l        U$ )a  
Start a text search, using text indexes.
Require: MongoDB server version 2.6+.

:param language:  The language that determines the list of stop words
    for the search and the rules for the stemmer and tokenizer.
    If not specified, the search uses the default language of the index.
    For supported languages, see
    `Text Search Languages <https://docs.mongodb.org/manual/reference/text-search-languages/#text-search-languages>`.
:param text_score:  True to have it return the text_score (available through get_text_score()), False to disable that
    Note that unless you order the results, leaving text_score=True may provide randomness in the returned documents
z0It is not possible to use search_text two times.z$searchz	$languagez$text__raw__N)	r\   rA   r   r   r3   r   r2   rI   rB   )rR   textlanguage
text_scorer`   query_kwargss         rU   search_textBaseQuerySet.search_text   sz     ::<   !STTIt,-(0%q'<)@AA $# $&0#rX   c                    U R                  5       nUR                  5       R                  S5      nUR                  " U0 UD6n [	        U5      n [	        U5        UR                  R                  S5      e! [
         a5    SUR                  R                  -  nUR                  R                  U5      ef = f! [
         a    Us $ f = f)a  Retrieve the matching object raising
:class:`~mongoengine.queryset.MultipleObjectsReturned` or
`DocumentName.MultipleObjectsReturned` exception if multiple results
and :class:`~mongoengine.queryset.DoesNotExist` or
`DocumentName.DoesNotExist` if no results are found.
r$   z!%s matching query does not exist.z&2 or more items returned, instead of 1)
r\   r   limitr   nextStopIterationr0   _class_nameDoesNotExistMultipleObjectsReturned)rR   r   r^   r`   resultr_   s         rU   rF   BaseQuerySet.get  s     ::<$$&,,Q/??F4e4	7(^F
	N
   884
 	
  	758J8J8V8VVC$$11#66	7  	M	s   A5 B7 5?B47CCc                 @    U R                   " S0 UD6R                  SS9$ )z5Create new object. Returns the saved object instance.T)force_insertrZ   )r0   save)rR   kwargss     rU   createBaseQuerySet.create"  s"    ~~'',,$,??rX   c                     U R                  5       nU R                  (       d  U R                  (       a  g US   nU$ ! [         a    Sn U$ f = f)z-Retrieve the first object matching the query.Nr   )r\   r?   rQ   
IndexError)rR   r`   r   s      rU   r   BaseQuerySet.first&  sM    ::<::	a[F   	F	s   < AAc                 ~   [        S5      nUc  0 nUnSn[        Xe5      (       d  [        UR                  U5      (       a  SnU/nU Hq  n[        XR                  5      (       d#  S[        U R                  5      -  n	[        U	5      eUR                  (       d  MS  UR                  (       a  Mf  Sn	[        U	5      e   U=(       d    0 n[        R                  R                  " U R                  4SU0UD6  U Vs/ s H  oR                  5       PM     n
n[        U R                  U5       nUR                  nU(       a  U
S   n
UR                   nSSS5         W" U
5      nU(       a  UR"                  /OUR$                  n[9        Xn5       H  u  nnUUl        M     U(       d<  [        R:                  R                  " U R                  4USS.UD6  U(       a  US   $ U$ U R=                  U5      nU Vs/ s H  nUR?                  U5      PM     nn[        R:                  R                  " U R                  4USS.UD6  U(       a  US   $ U$ s  snf ! , (       d  f       GN
= f! [&        R(                  R*                   a  nS	n[-        UU-  5      eSnAf[&        R(                  R.                   a  nS
n[/        UUR0                  -  5      eSnAf[&        R(                  R2                   aJ  nS	n[4        R6                  " S[        U5      5      (       a  Sn[-        UU-  5      e[        UU-  5      eSnAff = fs  snf )a  bulk insert documents

:param doc_or_docs: a document or list of documents to be inserted
:param load_bulk (optional): If True returns the list of document
    instances
:param write_concern: Extra keyword arguments are passed down to
        :meth:`~pymongo.collection.Collection.insert`
        which will be used as options for the resultant
        ``getLastError`` command.  For example,
        ``insert(..., {w: 2, fsync: True})`` will wait until at least
        two servers have recorded the write and will force an fsync on
        each server being written to.
:param signal_kwargs: (optional) kwargs dictionary to be passed to
    the signal calls.

By default returns document instances, set ``load_bulk`` to False to
return just ``ObjectIds``
DocumentNFTz.Some documents inserted aren't instances of %sz7Some documents have ObjectIds, use doc.update() instead	documentsr   zCould not save document (%s)zBulk write error: (%s)z^E1100[01] duplicate keyz(Tried to save duplicate unique keys (%s))r   loaded) r   r[   
issubclass	__class__r0   strr   pk_createdr
   pre_bulk_insertsendto_mongor   _collectioninsert_many
insert_oneinserted_idinserted_idspymongoerrorsDuplicateKeyErrorr   r   detailsOperationFailurerematchzippost_bulk_insertin_bulkrF   )rR   doc_or_docs	load_bulkwrite_concernsignal_kwargsr   docs
return_onedocr_   rawrT   insert_funcinserted_resultidserrmessagedoc_idr   obj_idresultss                        rU   insertBaseQuerySet.insert2  s   * !, M
d%%DNNH)M)MJ6DCc>>22FNNJ  %S))vvvclllO$S))  &+$$T^^UtU}U)-.#||~.t//?:$00K!f(33	 @	0)#.O  !,,-$11 . t>KCCF * $$))*.u@M (3q60S0LL%	7:;sV9==(s;  %%NN	
&-d	
>K	
 (wqz4W4_ /?? ~~// 	04G 3//~~,, 	8 /G 3;;!677~~.. 	04Gxx2CH== E$Ws]33 3//	0( <sI   8I)%I(I# 3L:
I #L7J!L72K!L7-AL22L7c                    U R                   S:X  a  USL d"  U R                  (       d  U R                  (       a  gU(       a  U R                   U R                  S.O0 nU R                   S:X  a  UR	                  SS5        U R
                  S;  a  U R
                  US'   U R                  (       a  U R                  US'   [        S
U R                  R                  U R                  S	.UD6nSU l        U$ )zCount the selected elements in the query.

:param with_limit_and_skip (optional): take any :meth:`limit` or
    :meth:`skip` that has been applied to this cursor into account when
    getting the count
r   F)r   skipr   N)r/   Nhint	collation)rT   r   rZ   )rJ   r?   rQ   rK   rg   rL   rM   r   ru   rT   _queryrI   )rR   with_limit_and_skipr   counts       rU   r   BaseQuerySet.count  s     KK1#u,zz{{ ;Ndkk4::6SU 	 ;;!JJw%::Z'!ZZF6N??"&//F; 
||..;;
 
  rX   c           	         U R                  5       nUR                  nUc  0 n[        R                  =(       aE    [        R                  R                  U5      =(       d    [        R                  R                  U5      nUR                  =(       d    UR                  =(       d    U=(       a    U(       + nU(       a$  SnU H  nUR                  " S0 UD6  US-  nM     U$ UR                  R                  S5      =(       d    0 n	[        U	R                  5       5      n	U	 H  u  pU
u  pUR                  R                  S5      (       a  M+  U[        :X  d  M7  UR                  " S0 US-   U 0D6nUR!                  S5      R#                  5       S:  d  Ms  [%        SUR&                  < SU< S	35      e   U	 GH8  u  pU
u  pUR                  R                  S5      (       a  M,  U[(        :X  a  Uc
  [+        5       OUnUR,                  UR,                  :X  a$  U H  nUR/                  UR0                  5        M      UR                  " S0 US-   U S
U0D6nUR#                  5       S:  a  UR                  XS9  M  M  U[2        :X  a0  UR                  " S0 US-   U 0D6R4                  " SSU0SU-  S0D6  M  U[6        :X  d  GM
  UR                  " S0 US-   U 0D6R4                  " SSU0SU-  U 0D6  GM;     [9        UR,                  U5       nUR;                  UR<                  5      nUR>                  (       a  UR@                  sSSS5        $  SSS5        g! , (       d  f       g= f)a  Delete the documents matched by the query.

:param write_concern: Extra keyword arguments are passed down which
    will be used as options for the resultant
    ``getLastError`` command.  For example,
    ``save(..., write_concern={w: 2, fsync: True}, ...)`` will
    wait until at least two servers have recorded the write and
    will force an fsync on the primary server.
:param _from_doc_delete: True when called from document delete therefore
    signals will have been triggered so don't loop.

:returns number of deleted documents
Nr   r#   delete_rulesabstract__inzCould not delete document (.z refers to it)pk__nin)r   cascade_refsr   z	unset__%szpull_all__%srZ   )!r\   r0   r
   signals_available
pre_deletehas_receivers_forpost_deleterK   rJ   deleterE   rF   listitemsr!   objectsr   r   r   __name__r    setr   addidr   rn   r"   r   delete_manyr   acknowledgeddeleted_count)rR   r   _from_doc_deleter   r`   r   has_delete_signalcall_document_deletecntr   
rule_entryruledocument_cls
field_namerefsrefrT   r   s                     rU   r   BaseQuerySet.delete  s    ::<   M $55 
005 :""44S9 	 NNBhooB1B #"" 	  C

+]+q   Jyy}}^4:L..01 !-J'1$L!!%%j11t|#++JzF/BD.IJ::a=&&(1,('00*>  !- !-J'1$L!!%%j11w(4(<su,??l&>&>>'$((0  (#++ !F*D)\J ::<!#KKmKW $$$C
V(;T'BCJJ "/4?*4La3P $$C
V(;T'BCJJ "/4BZ4OQU3V+ !-2 x33]Cz++HOO<F
 ""++ DC # DCCs   8M
M c           	      H   U(       d  U(       d  [        S5      eUc  0 nU R                  (       d  U R                  (       a  gU R                  5       nUR                  n	SU;   aO  [        US   [        5      (       a7  US    V
s/ s H&  n
[        R                  " UR                  40 SU
0D6PM(     nn
O![        R                  " UR                  40 UD6nU(       aD  SU	;   a>  SU;   a  UR                  R                  US   S'   OSUR                  R                  0US'    [        UR                  X45       nUR                  nU(       a  UR                  nU" XXS9nSSS5        U(       a  W$ WR                  (       a  UR                  S   $ gs  sn
f ! , (       d  f       N== f! [         R"                  R$                   a  n['        S	U-  5      eSnAf[         R"                  R(                   a/  n[+        U5      S
:X  a  Sn[        U5      e[        S	U-  5      eSnAff = f)a  Perform an atomic update on the fields matched by the query.

:param upsert: insert if document doesn't exist (default ``False``)
:param multi: Update multiple documents.
:param write_concern: Extra keyword arguments are passed down which
    will be used as options for the resultant
    ``getLastError`` command.  For example,
    ``save(..., write_concern={w: 2, fsync: True}, ...)`` will
    wait until at least two servers have recorded the write and
    will force an fsync on the primary server.
:param read_concern: Override the read concern for the operation
:param full_result: Return the associated ``pymongo.UpdateResult`` rather than just the number
    updated items
:param array_filters: A list of filters specifying which array elements an update should apply.
:param update: Django-style update keyword arguments

:returns the number of updated documents (unless ``full_result`` is True)
z'No update parameters, would remove dataNr   r   r+   z$set)upsertarray_filtersnUpdate failed (%s)zmulti not coded yetz'update() method requires MongoDB 1.1.3+)r   r?   rQ   r\   r   r[   r   r   rn   r0   r   r   r   
update_oneupdate_many
raw_resultr   r   r   r   r   r   )rR   r  multir   read_concernfull_resultr	  rn   r`   r^   urT   update_funcr   r   r   s                   rU   rn   BaseQuerySet.update  s   8 f !JKK M::::<:9t$
 $

  	**A   !3!3F	1~F*  F
 %%h&8&8CFCF fo)1););)G)Gvv&"((*<*<*H*H!Iv	='$$m(33","8"8K$& ""((-- #3  ~~// 	= !5!;<<~~.. 	=3x00C$W-- !5!;<<		=sH   -F F% 6'FF% .F% 
F"F% %H!G!H!2*HH!c           	          U R                   " SSSUUSS.UD6nUR                  S   (       a  U R                  5       nU$ U R                  R                  R                  UR                  5      nU$ )a'  Overwrite or add the first document matched by the query.

:param write_concern: Extra keyword arguments are passed down which
    will be used as options for the resultant
    ``getLastError`` command.  For example,
    ``save(..., write_concern={w: 2, fsync: True}, ...)`` will
    wait until at least two servers have recorded the write and
    will force an fsync on the primary server.
:param read_concern: Override the read concern for the operation
:param update: Django-style update keyword arguments

:returns the new or overwritten document
FT)r  r  r   r  r  updatedExistingrZ   )rn   r  rF   r0   r   with_idupserted_id)rR   r   r  rn   atomic_updaterS   s         rU   
upsert_oneBaseQuerySet.upsert_one_  sz      
'%
 
 ##$56xxzH  ~~--55m6O6OPHrX   c           	      2    U R                   " SUSUUUS.UD6$ )aD  Perform an atomic update on the fields of the first document
matched by the query.

:param upsert: insert if document doesn't exist (default ``False``)
:param write_concern: Extra keyword arguments are passed down which
    will be used as options for the resultant
    ``getLastError`` command.  For example,
    ``save(..., write_concern={w: 2, fsync: True}, ...)`` will
    wait until at least two servers have recorded the write and
    will force an fsync on the primary server.
:param full_result: Return the associated ``pymongo.UpdateResult`` rather than just the number
    updated items
:param array_filters: A list of filters specifying which array elements an update should apply.
:param update: Django-style update keyword arguments
    full_result
:returns the number of updated documents (unless ``full_result`` is True)
F)r  r  r   r  r	  rZ   )rn   )rR   r  r   r  r	  rn   s         rU   r  BaseQuerySet.update_one}  s3    2 {{ 
'#'
 
 	
rX   c                    U(       a  U(       a  [        S5      eU(       d  U(       d  U(       d  [        S5      eU R                  (       d  U R                  (       a  gU R                  5       nUR                  nU(       d!  [
        R                  " UR                  40 UD6nUR                  n	 U(       a  Sn
[        R                  " U
[        5        U(       a*  UR                  R                  " U4SU	0U R                  D6nOVU(       a  [        R                   nO[        R"                  nUR                  R$                  " UU4UU	UUS.U R                  D6n U(       a)  US   b!  U R                  R1                  US   5      US'   U$ Ub  U R                  R1                  U5      nU$ ! [&        R(                  R*                   a  n[-        SU-  5      eSnAf[&        R(                  R.                   a  n[        SU-  5      eSnAff = f)	a  Update and return the updated document.

Returns either the document before or after modification based on `new`
parameter. If no documents match the query and `upsert` is false,
returns ``None``. If upserting and `new` is false, returns ``None``.

If the full_response parameter is ``True``, the return value will be
the entire response object from the server, including the 'ok' and
'lastErrorObject' fields, rather than just the modified document.
This is useful mainly because the 'lastErrorObject' document holds
information about the command's execution.

:param upsert: insert if document doesn't exist (default ``False``)
:param full_response: return the entire response object from the
    server (default ``False``, not available for PyMongo 3+)
:param remove: remove rather than updating (default ``False``)
:param new: return updated rather than original document
    (default ``False``)
:param array_filters: A list of filters specifying which array elements an update should apply.
:param update: Django-style update keyword arguments
z&Conflicting parameters: remove and newz2No update parameters, must either update or removeNzEWith PyMongo 3+, it is not possible anymore to get the full response.sort)r  r  return_documentr	  r  value)r   r?   rQ   r\   r   r   rn   r0   r7   warningswarnDeprecationWarningr   find_one_and_delete_cursor_argsr   AFTERBEFOREfind_one_and_updater   r   r   r   r   rz   )rR   r  full_responseremovenewr	  rn   r`   r^   r  r_   r   
return_docr   s                 rU   modifyBaseQuerySet.modify  s   > c !IJJfV !UVV::::<%%h&8&8CFCF!!	=]c#56!--AA $(,(9(9 !/!5!5J!/!6!6J!--AA "$."/ '' g*"&..":":6'?"Kw
  !11&9 ~~// 	= !5!;<<~~.. 	= !5!;<<	=s,   .AF) AF) )H	G!H	6HH	c                     U R                  5       nUR                  (       a  Sn[        U5      eUR                  US9R	                  5       $ )zRetrieve the object matching the id provided.  Uses `object_id` only
and raises InvalidQueryError if a filter has been applied. Returns
`None` if no document exists with that id.

:param object_id: the value for the id of the document to look up
z*Cannot use a filter whilst using `with_id`)r   )r\   r3   r   r   r   )rR   	object_idr`   r_   s       rU   r  BaseQuerySet.with_id  sB     ::<>C#C((),2244rX   c                    0 nU R                   R                  " SSU0040 U R                  D6nU R                  (       a:  U H2  nU R	                  U R
                  R                  U5      5      X$S   '   M4     U$ U R                  (       a  U H
  nXBUS   '   M     U$ U H,  nU R
                  R                  UU R                  S9X$S   '   M.     U$ )zRetrieve a set of documents by their ids.

:param object_ids: a list or tuple of ObjectId's
:rtype: dict of ObjectId's as keys and collection-specific
        Document subclasses as values.
_idr,   rr   )	r   findr&  r>   ry   r0   rz   r@   rs   )rR   
object_idsdoc_mapr   r   s        rU   r   BaseQuerySet.in_bulk  s     $$eeZ-@%AWTEVEVW<<&*&6&6t~~7O7OPS7T&UE
#   &)E
#   &*nn&>&>&*&<&< '? 'E
#  rX   c                 4    U R                  5       nSUl        U$ )zReturns a queryset that never returns any objects and no query will be executed when accessing the results
inspired by django none() https://docs.djangoproject.com/en/dev/ref/models/querysets/#none
T)r\   r?   r   s     rU   noneBaseQuerySet.none  s     ::<rX   c                     U R                   R                  R                  S5      SL a  SU R                   R                  0U l        U $ )zaFilter for only the instances of this specific document.

Do NOT return any inherited documents.
r*   Tr+   )r0   rE   rF   r   r4   r   s    rU   no_sub_classesBaseQuerySet.no_sub_classes  s=    
 >>##$78D@%t~~'A'ABDOrX   c                     [        U R                  U5       nUR                  5       nSSS5        U R                  U R	                  U R                  W5      5      $ ! , (       d  f       N9= f)zThis method is for controlling which database the QuerySet will be
evaluated against if you are using more than one database.

:param alias: The database alias
N)r   r0   rm   _clone_intor   )rR   aliasclsrT   s       rU   usingBaseQuerySet.using)  sR     t~~u-,,.J . t~~z JKK .-s   A
A)c                 l    U R                  U R                  U R                  U R                  5      5      $ )z&Create a copy of the current queryset.)r@  r   r0   r1   r   s    rU   r\   BaseQuerySet.clone5  s(    t~~t?S?S TUUrX   c                 N   [        U[        5      (       d  [        SUR                  -  5      eSnU H.  n[	        X5      n[        X[        R                  " U5      5        M0     U R                  Ul        U R                  (       a  U R                  R                  5       Ul        U$ )zCopy all the relevant properties of this queryset to
a new queryset (which has to be an instance of
:class:`~mongoengine.queryset.base.BaseQuerySet`).
z$%s is not a subclass of BaseQuerySet)r2   r4   r?   r3   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r@   rJ   rK   rQ   rL   rM   rA   rB   rO   rP   rN   )
r[   r   r   r   getattrsetattrrf   rD   rI   r\   )rR   new_qs
copy_propspropvals        rU   r@  BaseQuerySet._clone_into9  s    
 &,// 6H 

8 D$%CF$))C.1  %)$H$H!!%!1!1!7!7!9FrX   c                 J    US-  nU R                  5       nUR                  X!S9$ )zHandles dereferencing of :class:`~bson.dbref.DBRef` objects or
:class:`~bson.object_id.ObjectId` a maximum depth in order to cut down
the number queries to mongodb.
r#   )	max_depth)r\   _dereference)rR   rP  r`   s      rU   select_relatedBaseQuerySet.select_relatedj  s,     	Q	::<$$X$CCrX   c                     U R                  5       nXl        SUl        UR                  (       a%  UR                  R	                  UR                  5        U$ )a  Limit the number of returned documents to `n`. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).

:param n: the maximum number of objects to return if n is greater than 0.
When 0 is passed, returns all the documents in the cursor
F)r\   rJ   rQ   rI   r   rR   r
  r`   s      rU   r   BaseQuerySet.limitt  sC     ::<   &&x7rX   c                     U R                  5       nXl        UR                  (       a%  UR                  R                  UR                  5        U$ )zSkip `n` documents before returning the results. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[5:]``).

:param n: the number of objects to skip before returning results
)r\   rK   rI   r   rU  s      rU   r   BaseQuerySet.skip  s<     ::<   %%hnn5rX   c                     U R                  5       nXl        UR                  (       a%  UR                  R                  UR                  5        U$ )a  Added 'hint' support, telling Mongo the proper index to use for the
query.

Judicious use of hints can greatly improve query performance. When
doing a query on multiple fields (at least one of which is indexed)
pass the indexed field as a hint to the query.

Hinting will not do anything if the corresponding index does not exist.
The last hint applied to this cursor takes precedence over all others.
)r\   rL   rI   r   )rR   indexr`   s      rU   r   BaseQuerySet.hint  s<     ::<   %%hnn5rX   c                     U R                  5       nXl        UR                  (       a  UR                  R                  U5        U$ )a  
Collation allows users to specify language-specific rules for string
comparison, such as rules for lettercase and accent marks.
:param collation: `~pymongo.collation.Collation` or dict with
following fields:
    {
        locale: str,
        caseLevel: bool,
        caseFirst: str,
        strength: int,
        numericOrdering: bool,
        alternate: str,
        maxVariable: str,
        backwards: str
    }
Collation should be added to indexes like in test example
)r\   rM   rI   r   )rR   r   r`   s      rU   r   BaseQuerySet.collation  s7    $ ::<'  **95rX   c                     U R                  5       nXl        UR                  (       a%  UR                  R                  UR                  5        U$ )zLimit the number of documents returned in a single batch (each
batch requires a round trip to the server).

See https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html#pymongo.cursor.Cursor
for details.

:param size: desired size of each batch.
)r\   rN   rI   
batch_size)rR   sizer`   s      rU   r_  BaseQuerySet.batch_size  s?     ::<#   ++H,@,@ArX   c                    U R                  5       n U R                  U/5      R                  5       nUR                  R                  U5      nU R                  (       d  U$ U R                  USXR                  S9nU R                  R                  R                  UR                  SS5      S   5      nSn[        S5      n[        S5      n[        S5      n	[        XX5      (       a  [        US	U5      n[        XWU	45      (       a  [        US
S5      nSU;   a  UR                  S5      SS  Hh  n
U(       a  [        XWU	45      (       a  Un[        XZU5      n[        XX5      (       a  [        US	U5      n[        XWU	45      (       d  M[  [        US
S5      nMj     U(       a)  [        XWU	45      (       a  U Vs/ s H
  o" S0 UD6PM     nnU$ ! [         a     GNf = fs  snf )zReturn a list of distinct values for a given field.

:param field: the field to select distinct values from

.. note:: This is a command and won't take ordering or limit into
   account.
r#   )nameinstancer   r   NEmbeddedDocumentField	ListFieldGenericEmbeddedDocumentFieldfielddocument_typerZ   )r\   _fields_to_dbfieldsrg   r   ru   distinctrs   rQ  r0   _fieldsrF   splitr   r[   rH  )rR   rh  r`   
raw_valuesrk  	doc_fieldrd  re  rf  rg  
field_partr   s               rU   rk  BaseQuerySet.distinct  s    ::<	,,eW599;E %%..u5
%%$$Z$XNN**..u{{3/B1/EF	 !..E F!+.	'45S'T$i++	7I>Ii9U!VWWy/4@H %<#kk#.qr2

7ST! ! !)I#I9E	i33 '	7I FI7ST   'y/4HH 3  
/KL
 
 4<<8C38H<Y  		T =s    G
 5G

GGc                 p    U Vs0 s H  o"[         R                  _M     nnU R                  " S0 UD6$ s  snf )a  Load only a subset of this document's fields. ::

    post = BlogPost.objects(...).only('title', 'author.name')

.. note :: `only()` is chainable and will perform a union ::
    So with the following it will fetch both: `title` and `author.name`::

        post = BlogPost.objects.only('title').only('author.name')

:func:`~mongoengine.queryset.QuerySet.all_fields` will reset any
field filters.

:param fields: fields to include
)T)r   ONLYfieldsrR   rt  fs      rU   onlyBaseQuerySet.only  s8     399&Q^(((&9{{*6** :   3c                 p    U Vs0 s H  o"[         R                  _M     nnU R                  " S0 UD6$ s  snf )a  Opposite to .only(), exclude some document's fields. ::

    post = BlogPost.objects(...).exclude('comments')

.. note :: `exclude()` is chainable and will perform a union ::
    So with the following it will exclude both: `title` and `author.name`::

        post = BlogPost.objects.exclude('title').exclude('author.name')

:func:`~mongoengine.queryset.QuerySet.all_fields` will reset any
field filters.

:param fields: fields to exclude
rZ   )r   EXCLUDErt  ru  s      rU   excludeBaseQuerySet.exclude   s8     6<<V^+++V<{{$V$$ =ry  c           	         SS/n/ nUR                  5        HZ  u  pVUR                  S5      nUS   U;   a  UR                  S5      nSU-   U0nSR                  U5      nUR	                  XV45        M\     S n	[        XIS9n
U R                  5       n[        R                  " U
S	 5       HJ  u  plU VVs/ s H  u  pUPM	     n
nnUR                  U
5      n
U=R                  [        U
WUS
9-  sl
        ML     U$ s  snnf )a  Manipulate how you load this document's fields. Used by `.only()`
and `.exclude()` to manipulate which fields to retrieve. If called
directly, use a set of kwargs similar to the MongoDB projection
document. For example:

Include only a subset of fields:

    posts = BlogPost.objects(...).fields(author=1, title=1)

Exclude a specific field:

    posts = BlogPost.objects(...).fields(comments=0)

To retrieve a subrange or sublist of array elements,
support exist for both the `slice` and `elemMatch` projection operator:

    posts = BlogPost.objects(...).fields(slice__comments=5)
    posts = BlogPost.objects(...).fields(elemMatch__comments="test")

:param kwargs: A set of keyword arguments identifying what to
    include, exclude, or slice.
rt   	elemMatch__r   $r   c                 :    U u  p[        U[        5      (       a  U$ g)Nr$   )r[   rx   )field_tuple_r!  s      rU   	_sort_key&BaseQuerySet.fields.<locals>._sort_keyX  s    "HA%%%rX   )r|   c                     U S   $ )Nr#   rZ   )xs    rU   <lambda>%BaseQuerySet.fields.<locals>.<lambda>c  s    !rX   )r!  _only_called)r   rm  rg   joinappendsortedr\   	itertoolsgroupbyrj  r6   r   )rR   r  r   	operatorscleaned_fieldsr|   r!  partsopr  rt  r`   grouprh  s                 rU   rt  BaseQuerySet.fields2  s    2 k*	 ,,.JCIIdOEQx9$YYq\r5)((5/C!!3,/ )	 6 ::<%--fnELE056eF611&9F##~e,( # F  7s   3C9c                 j    U R                  5       n[        UR                  R                  S9Ul        U$ )zInclude all fields. Reset all previously calls of .only() or
.exclude(). ::

    post = BlogPost.objects.exclude('comments').all_fields()
r-   )r\   r   r6   r.   r   s     rU   
all_fieldsBaseQuerySet.all_fieldsl  s2     ::<"0#22AA#
 rX   r   c                6   U(       a  U(       a  [        S5      eU R                  5       nUR                  nU(       a  UnOUR                  U5      nUR                  (       a1  U(       a  UR                  R                  U5        OU(       a  SUl        XSl        U$ )a  Order the :class:`~mongoengine.queryset.QuerySet` by the given keys.

The order may be specified by prepending each of the keys by a "+" or
a "-". Ascending order is assumed if there's no prefix.

If no keys are passed, existing ordering is cleared instead.

:param keys: fields to order the query results by; keys may be
    prefixed with "+" or a "-" to determine the ordering direction.
:param __raw__: a raw pymongo "sort" argument (provided as a list of (key, direction))
    see 'key_or_list' in `pymongo.cursor.Cursor.sort doc <https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html#pymongo.cursor.Cursor.sort>`.
    If both keys and __raw__ are provided, an exception is raised
z2Can not use both keys and __raw__ with order_by() N)r   r\   r7   _get_order_byrI   r  )rR   r   keysr`   old_orderingnew_orderings         rU   r   BaseQuerySet.order_byx  s{     t !UVV::<))"L#11$7L$$)),7
 '+$)rX   c                 4    U R                  5       n0 Ul        U$ )a2  Clear the default "_cls" query.

By default, all queries generated for documents that allow inheritance
include an extra "_cls" clause. In most cases this is desirable, but
sometimes you might achieve better performance if you clear that
default query.

Scan the code for `_cls_query` to get more details.
)r\   r4   r   s     rU   clear_cls_queryBaseQuerySet.clear_cls_query  s     ::< rX   c                 &    U R                  SU5      $ )zsAdd a comment to the query.

See https://www.mongodb.com/docs/manual/reference/method/cursor.comment/
for details.
comment_chainable_method)rR   r   s     rU   r  BaseQuerySet.comment  s     %%i66rX   c                 6    U R                   R                  5       $ )zVReturn an explain plan record for the
:class:`~mongoengine.queryset.QuerySet` cursor.
)ru   explainr   s    rU   r  BaseQuerySet.explain  s     ||##%%rX   c                 l    Sn[         R                  " U[        5        U R                  5       nXl        U$ )zhEnable or disable snapshot mode when querying.

:param enabled: whether or not snapshot mode is enabled
zAsnapshot is deprecated as it has no impact when using PyMongo 3+.)r"  r#  r$  r\   r8   )rR   enabledr_   r`   s       rU   snapshotBaseQuerySet.snapshot  s/    
 Rc-.::<$rX   c                 2    U R                  5       nXl        U$ )zEnable or disable the use of temporary files on disk while processing a blocking sort operation.
 (To store data exceeding the 100 megabyte system memory limit)

:param enabled: whether or not temporary files on disk are used
)r\   r:   rR   r  r`   s      rU   allow_disk_useBaseQuerySet.allow_disk_use  s     ::<#* rX   c                 2    U R                  5       nXl        U$ )zEnable or disable the default mongod timeout when querying. (no_cursor_timeout option)

:param enabled: whether or not the timeout is used
)r\   r9   r  s      rU   timeoutBaseQuerySet.timeout  s    
 ::<#rX   c                 X    [        SU5        U R                  5       nXl        SUl        U$ )zwChange the read_preference when querying.

:param read_preference: override ReplicaSetConnection-level
    preference.
read_preferenceN)r   r\   r;   rI   )rR   r  r`   s      rU   r  BaseQuerySet.read_preference  s-     	!!2OD::<$3!#rX   c                     Ub$  [        U[        5      (       d  [        U< S35      eU R                  5       nUb  [	        S0 UD6OSUl        SUl        U$ )zqChange the read_concern when querying.

:param read_concern: override ReplicaSetConnection-level
    preference.
Nz is not a valid read concern.rZ   )r[   r   r{   r\   r	   r<   rI   )rR   r  r`   s      rU   r  BaseQuerySet.read_concern  s^     #J|W,M,M|..KLMM::<+7+CK',' 	  $rX   c                     U R                  5       n[        U5      Ul        U(       a  UR                  " U6 nU$ UR	                  5       nU$ )a  Instead of returning Document instances, return either a specific
value or a tuple of values in order.

Can be used along with
:func:`~mongoengine.queryset.QuerySet.no_dereference` to turn off
dereferencing.

.. note:: This effects all results and can be unset by calling
          ``scalar`` without arguments. Calls ``only`` automatically.

:param fields: One or more fields to return instead of a Document.
)r\   r   r>   rw  r  )rR   rt  r`   s      rU   scalarBaseQuerySet.scalar  sH     ::<<}}f-H   **,HrX   c                      U R                   " U6 $ )zAn alias for scalar)r  )rR   rt  s     rU   values_listBaseQuerySet.values_list  s    {{F##rX   c                 4    U R                  5       nSUl        U$ )zInstead of returning Document instances, return raw values from
pymongo.

This method is particularly useful if you don't need dereferencing
and care primarily about the speed of data retrieval.
T)r\   r@   r   s     rU   
as_pymongoBaseQuerySet.as_pymongo  s     ::<#rX   c                 &    U R                  SU5      $ )zWait `ms` milliseconds before killing the query on the server

:param ms: the number of milliseconds before killing the query on the server
max_time_msr  )rR   mss     rU   r  BaseQuerySet.max_time_ms  s    
 %%mR88rX   c                     SU;  a$  [         R                  " S[        5        [        US'   [        R
                  " U R                  5       /UQ70 UD6$ )zConverts a queryset to JSONjson_optionsa  No 'json_options' are specified! Falling back to LEGACY_JSON_OPTIONS with uuid_representation=PYTHON_LEGACY. For use with other MongoDB drivers specify the UUID representation to use. This will be changed to uuid_representation=UNSPECIFIED in a future release.)r"  r#  r$  r   r   dumpsr  )rR   argsr   s      rU   to_jsonBaseQuerySet.to_json%  sM    'MMG
 # &9F>"t0B4B6BBrX   c                     [         R                  " U5      nU Vs/ s H  o0R                  R                  U5      PM     sn$ s  snf )z%Converts json data to unsaved objects)r   loadsr0   rz   )rR   	json_datason_datadatas       rU   	from_jsonBaseQuerySet.from_json3  s5    ??9-;CD84((.8DDDs   $Ac                    [        U[        5      =(       d    [        U5      n[        U[        5      (       a  U/O
[        U5      nU(       a  Sn[        R
                  " U[        5        XR-  n/ nU R                  (       d  U R                  (       a(  UR                  SS05        UR                  SSS005        U R                  (       a  UR                  SU R                  05        U R                  (       a&  UR                  S[        U R                  5      05        U R                  b3  UR                  SU R                  U R                  =(       d    S-   05        U R                  b  UR                  S	U R                  05        Xu-   nU R                  n	U R                  c  U R                   b.  U R                  R#                  U R                  U R                   S
9n	U	R$                  " U4S0 0UD6$ )a	  Perform an aggregate function based on your queryset params

:param pipeline: list of aggregation commands,
    see: https://www.mongodb.com/docs/manual/core/aggregation-pipeline/
:param suppl_pipeline: unpacked list of pipeline (added to support deprecation of the old interface)
    parameter will be removed shortly
:param kwargs: (optional) kwargs dictionary to be passed to pymongo's aggregate call
    See https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.aggregate
zCalling .aggregate() with un unpacked list (*pipeline) is deprecated, it will soon change and will expect a list (similar to pymongo.Collection.aggregate interface), see documentationz$limitr#   $matchz$exprFz$sortr   z$skipr  r  cursor)r[   dictboolr   r"  r#  r$  r?   rQ   r  r   r7   rJ   rK   r   r;   r<   with_options	aggregate)
rR   pipelinesuppl_pipeliner   using_deprecated_interfaceuser_pipeliner_   initial_pipelinefinal_pipelinerT   s
             rU   r  BaseQuerySet.aggregate8  s    &0$%?%W4CW"&04&@&@
d8n% LCMM#12'::##XqM2##X/?$@A;;##Xt{{$;<>>##Wd4>>.B$CD;;"
 ##Xt{{djjoA/N$OP::!##Wdjj$9:)9%%
  ,0B0B0N))66 $ 5 5DDVDV 7 J ##NH2HHHrX   c              #     #    U R                  5       n[        S5      n0 n	[        U[        5      (       a  UR                  n	[        U5      n[        UR                  U5      U	=(       d    S5      n0 n
[        U[        5      (       a  UR                  n
[        U5      nUR                  U5      n[        X=(       d    S5      nSUR                  0nU(       aW  0 n[        U[        5      (       a  UR                  n[        U5      nUR                  U5      n[        X=(       d    S5      nXLS'   U(       a  XlS'   U(       a  X\S'   US:X  a  UR                  (       d
  SnSS	0US
'   OSn[        U[
        5      (       a  X<S
'   O[        U[        5      (       a  / nS H0  nUR                  U5      nU(       d  M  UR                  UU45          O   [        S5      eUR                  S5      n/ SQnU(       a)  UR                  S[        U5      R                  45        US	 U H0  nUR                  U5      nU(       d  M  UR                  UU45        M2     [        U5      US
'   UR                   R#                  5       nUR%                  UR                   R'                  5       UUS.UE5      nU(       a  US   nOZ[        US   [
        5      (       a  UUS      R)                  5       nO+US   nUR*                  US      US      R)                  5       nUR                  (       a  UR-                  UR                  5      nU H*  nU" UR                   UR.                  US   US   5      v   M,     g7f)a  Perform a map/reduce query using the current query spec
and ordering. While ``map_reduce`` respects ``QuerySet`` chaining,
it must be the last call made, as it does not return a maleable
``QuerySet``.

See the :meth:`~mongoengine.tests.QuerySetTest.test_map_reduce`
and :meth:`~mongoengine.tests.QuerySetTest.test_map_advanced`
tests in ``tests.queryset.QuerySetTest`` for usage examples.

:param map_f: map function, as :class:`~bson.code.Code` or string
:param reduce_f: reduce function, as
                 :class:`~bson.code.Code` or string
:param output: output collection name, if set to 'inline' will return
   the results inline. This can also be a dictionary containing output options
   see: https://www.mongodb.com/docs/manual/reference/command/mapReduce/#mongodb-dbcommand-dbcmd.mapReduce
:param finalize_f: finalize function, an optional function that
                   performs any post-reduction processing.
:param scope: values to insert into map/reduce global scope. Optional.
:param limit: number of objects from current query to provide
              to map/reduce method

Returns an iterator yielding
:class:`~mongoengine.document.MapReduceDocument`.
MapReduceDocumentNr^   finalizescoper   inlineTr#   outF)replacemergereducez#actionData not specified for outputdb_alias)dbsharded	nonAtomicr  r   )	mapReducemapr  r   r   rT   r4  r!  )r\   r   r[   r   r  r   _sub_js_fieldsr   r7   r  rF   r  r   r   rc  r   r0   _get_dbcommand_get_collection_namer5  clientr  r   )rR   map_freduce_foutput
finalize_fr   r  r`   r  map_f_scopereduce_f_scopereduce_f_codemr_argsfinalize_f_scopefinalize_f_coder  ordered_outputpartr!  r  remaing_argsr  r   r   infor   s                             rU   
map_reduceBaseQuerySet.map_reducek  s     6 ::<)*=>eT""++KJEX,,U3[5HDIh%%%^^N8}H //9'=>HOO,!*d++#-#3#3  _
&55jAOo/G4HJ",J$G$GXh&8&8F&]GENF&#&&!'FD))!#:D"JJt,Eu&--tUm<	 ; ))NOO!::j1="))41A1F1F*GH$Q(D"JJt,Eu&--tUm< )
 "%^!4'')%//DDF" 	
 )$D&*C00&*+002h'yyd,T,-?@EEG99X//0DC#""H$8$8#e*c'l  s   F2M08BM0>D2M0c                    U R                  5       nUR                  U5      nU Vs/ s H  oTR                  R                  U5      PM     nnUR                  R	                  5       nXc=(       d    0 S.nUR
                  nUR                  (       a  UR                  US'   XS'   [        XS9nUR                  R                  5       n	U	R                  SXS9R                  S5      $ s  snf )aS  Execute a Javascript function on the server. A list of fields may be
provided, which will be translated to their correct names and supplied
as the arguments to the function. A few extra variables are added to
the function's scope: ``collection``, which is the name of the
collection in use; ``query``, which is an object representing the
current query; and ``options``, which is an object containing any
options specified as keyword arguments.

As fields in MongoEngine may use different names in the database (set
using the :attr:`db_field` keyword argument to a :class:`Field`
constructor), a mechanism exists for replacing MongoEngine field names
with the database field names in Javascript code. When accessing a
field, use square-bracket notation, and prefix the MongoEngine field
name with a tilde (~).

:param code: a string of Javascript code to execute
:param fields: fields that you will be using in your function, which
    will be passed in to your function as arguments
:param options: options that you want available to the function
    (accessed in Javascript through the ``options`` object)
)rT   optionsz$wherer^   )r  eval)r  retval)r\   r  r0   _translate_field_namer  r   r5   r   r  r  rF   )
rR   codert  r	  r`   rv  rT   r  r^   r  s
             rU   exec_jsBaseQuerySet.exec_js  s    , ::<&&t,GMNv!$$::1=vN''<<>
)mD!!&44E(OgD&'')zz&$z488BB Os   $C%c                 T    U R                  5       nUR                  U5      nXl        U$ )aY  Filter ``QuerySet`` results with a ``$where`` clause (a Javascript
expression). Performs automatic field name substitution like
:meth:`mongoengine.queryset.Queryset.exec_js`.

.. note:: When using this mode of query, the database will call your
          function, or evaluate your predicate clause, for each object
          in the collection.
)r\   r  r5   )rR   where_clauser`   s      rU   whereBaseQuerySet.where  s*     ::<..|<!-rX   c                    U R                  U/5      R                  5       nSU R                  0SSSSU-   0S.0/n[        S5      nUR	                  S5      nU R
                  R                  U5      n[        US	   U5      (       a  UR                  S
SSU-   05        [        U R
                  R                  5       R                  U5      5      nU(       a  US   S   $ g)zSum over the values of the specified field.

:param field: the field to sum over; use dot notation to refer to
    embedded document fields
r  $groupsumz$sumr  r4  totalrf  r   r/   r#   $unwindr   r  rj  rg   r   r   rm  r0   _lookup_fieldr[   r   tuplerm   r  rR   rh  db_fieldr  rf  field_partsfield_instancesr   s           rU   r  BaseQuerySet.sum  s     ++UG488:t{{#uh/GHI
 "+.	kk#&..66{Cob)955OOA	3;78t~~557AA(KL!9W%%rX   c                    U R                  U/5      R                  5       nSU R                  0SSSSU-   0S.0/n[        S5      nUR	                  S5      nU R
                  R                  U5      n[        US	   U5      (       a  UR                  S
SSU-   05        [        U R
                  R                  5       R                  U5      5      nU(       a  US   S   $ g)zAverage over the values of the specified field.

:param field: the field to average over; use dot notation to refer to
    embedded document fields
r  r  avgz$avgr  r  rf  r   r/   r#   r  r   r  r  r  s           rU   averageBaseQuerySet.average6  s     ++UG488:t{{#uh/GHI
 "+.	kk#&..66{Cob)955OOA	3;78t~~557AA(KL!9W%%rX   c                 L    U(       a  U R                  XS9$ U R                  XS9$ )a  Returns a dictionary of all items present in a field across
the whole queried set of documents, and their corresponding frequency.
This is useful for generating tag clouds, or searching documents.

.. note::

    Can only do direct simple mappings and cannot map across
    :class:`~mongoengine.fields.ReferenceField` or
    :class:`~mongoengine.fields.GenericReferenceField` for more complex
    counting a manual map reduce call is required.

If the field is a :class:`~mongoengine.fields.ListField`, the items within
each list will be counted individually.

:param field: the field to use
:param normalize: normalize the results so they add to 1.0
:param map_reduce: Use map_reduce over exec_js
)	normalize)_item_frequencies_map_reduce_item_frequencies_exec_js)rR   rh  r'  r  s       rU   item_frequenciesBaseQuerySet.item_frequenciesP  s/    & 44U4PP--e-IIrX   c                 2   U R                   (       d  U R                  (       a  [        e[        U R                  5      nU R
                  (       a  U$ U R                  R                  UU R                  S9nU R                  (       a  U R                  U5      $ U$ )z;Wrap the result in a :class:`~mongoengine.Document` object.rr   )r?   rQ   r   r   ru   r@   r0   rz   rs   r>   ry   )rR   raw_docr   s      rU   __next__BaseQuerySet.__next__i  su    ::t||$Nnn&&"44 ' 

 <<##C((
rX   c                 F    SU l         U R                  R                  5         g)z+Rewind the cursor to its unevaluated state.FN)r=   ru   rewindr   s    rU   r1  BaseQuerySet.rewind}  s    
rX   c                     U R                   $ )zvProperty that returns the collection object. This allows us to
perform operations only if the collection is accessed.
)r1   r   s    rU   r   BaseQuerySet._collection  s    
 ###rX   c                    SnU R                   (       a  Sn[        R                  " U[        5        0 nU R                  (       d  SUS'   U R
                  (       a  SUS'   U R                  (       a  U R                  R                  5       X1'   U R                  (       a#  X;  a  0 X1'   U R                  (       a	  SS0X1   S'   U$ )	N
projectionz<The snapshot option is not anymore available with PyMongo 3+Tno_cursor_timeoutr  $meta	textScore_text_score)
r8   r"  r#  r$  r9   r:   r6   as_dictrA   rB   )rR   fields_namer_   cursor_argss       rU   r&  BaseQuerySet._cursor_args  s    " >>PCMM#12}}/3K+,,0K()'+':':'B'B'DK$-+-(&&;BK:P(7rX   c                    U R                   b  U R                   $ U R                  c  U R                  bY  U R                  R	                  U R                  U R                  S9R
                  " U R                  40 U R                  D6U l         O6U R                  R
                  " U R                  40 U R                  D6U l         U R                  (       a6  U R                  U R                  5      nU R                   R                  U5        U R                  (       a&  U R                   R                  U R                  5        OnU R                  ca  U R                  R                  S   (       aC  U R                  U R                  R                  S   5      nU R                   R                  U5        U R                   b%  U R                   R#                  U R                   5        U R$                  b%  U R                   R'                  U R$                  5        U R(                  S:w  a%  U R                   R+                  U R(                  5        U R,                  b%  U R                   R/                  U R,                  5        U R0                  b%  U R                   R3                  U R0                  5        U R4                  b%  U R                   R7                  U R4                  5        U R                   $ )z>Return a PyMongo cursor object corresponding to this queryset.r  orderingr/   )rI   r;   r<   r   r  r5  r   r&  r5   r  r  r7   r  r0   rE   r  rJ   r   rK   r   rL   r   rM   r   rN   r_  rP   r  )rR   r  orders      rU   ru   BaseQuerySet._cursor  s4   
 '###   ,0B0B0N#//<< $ 5 5DDVDV  =  d ;; 5"&"3"3 5D  $//44T[[VDDUDUVD ..t/A/ABL""<0 >>!!$..1^^#(<(<Z(H&&t~~';';J'GHE!!%(;;"""4;;/::!!!$**-::!!$**-??&&&t7'''(8(89==$$$T]]3rX   c                 "    U R                  5       $ )z;Essential for chained queries with ReferenceFields involved)r\   )rR   memos     rU   __deepcopy__BaseQuerySet.__deepcopy__  s    zz|rX   c                 j   U R                   c  U R                  R                  U R                  5      U l         U R                  (       a`  SU R                   ;   a+  SU R                  U R                   /0U l         U R                   $ U R                   R                  U R                  5        U R                   $ )Nr+   z$and)r2   r3   to_queryr0   r4   rn   r   s    rU   r   BaseQuerySet._query  s    $ $ 8 8 HDT...)/$//4CTCT1U(VD%     %%,,T__=   rX   c                 f    U R                   (       d  [        S5      " 5       U l         U R                   $ )NDeReference)rC   r   r   s    rU   rQ  BaseQuerySet._dereference  s'    !!!.}!=!?D!!!rX   c                 `    [        U R                  5      (       + nU=(       a    U R                  $ r   )r   r0   rD   )rR   should_derefs     rU   rs   BaseQuerySet._auto_dereference  s$    <T^^LL7 7 77rX   c                 4    U R                  5       nSUl        U$ )z<Turn off any dereferencing for the results of this queryset.F)r\   rD   r   s     rU   no_dereferenceBaseQuerySet.no_dereference  s    ::<&+#rX   c                    SR                  US9nSnU R                  X4S5      n0 nU HU  nUR                  n[        U[        5      (       a  [        U5      U:X  a  [        U5      n[        UR                  5      Xh'   MW     U(       aJ  [        UR                  5       5      n	UR                  5        V
Vs0 s H  u  pU
[	        U5      U	-  _M     nn
nU$ s  snn
f )Na  
            function() {{
                var path = '{{{{~{field}}}}}'.split('.');
                var field = this;

                for (p in path) {{
                    if (typeof field != 'undefined')
                       field = field[path[p]];
                    else
                       break;
                }}
                if (field && field.constructor == Array) {{
                    field.forEach(function(item) {{
                        emit(item, 1);
                    }});
                }} else if (typeof field != 'undefined') {{
                    emit(field, 1);
                }} else {{
                    emit(null, 1);
                }}
            }}
        )rh  a%  
            function(key, values) {
                var total = 0;
                var valuesSize = values.length;
                for (var i=0; i < valuesSize; i++) {
                    total += parseInt(values[i], 10);
                }
                return total;
            }
        r  )
formatr  r|   r[   floatrx   r!  r  valuesr   )rR   rh  r'  map_funcreduce_funcrV  frequenciesrv  r|   r   kvs               rU   r(  )BaseQuerySet._item_frequencies_map_reduce  s    * F  
+ 	0	 AA%%C#u%%s8s?c(C"177|K  **,-E;F;L;L;NO;N411eAh..;NKO Ps   4Cc                    SnU R                  X15      u  pEnUR                  5        VVs0 s H   u  pxUR                  U5      [        U5      _M"     n	nnU(       a1  U	R                  5        VVs0 s H  u  pxU[	        U5      U-  _M     n	nn0 n
U	R                  5        H8  u  px[        U[        5      (       a  [        U5      U:X  a  [        U5      nXU'   M:     U
$ s  snnf s  snnf )zUses exec_js to executeaa  
            function(path) {
                var path = path.split('.');

                var total = 0.0;
                db[collection].find(query).forEach(function(doc) {
                    var field = doc;
                    for (p in path) {
                        if (field)
                            field = field[path[p]];
                         else
                            break;
                    }
                    if (field && field.constructor == Array) {
                       total += field.length;
                    } else {
                       total++;
                    }
                });

                var frequencies = {};
                var types = {};
                var inc = 1.0;

                db[collection].find(query).forEach(function(doc) {
                    field = doc;
                    for (p in path) {
                        if (field)
                            field = field[path[p]];
                        else
                            break;
                    }
                    if (field && field.constructor == Array) {
                        field.forEach(function(item) {
                            frequencies[item] = inc + (isNaN(frequencies[item]) ? 0: frequencies[item]);
                        });
                    } else {
                        var item = field;
                        types[item] = item;
                        frequencies[item] = inc + (isNaN(frequencies[item]) ? 0: frequencies[item]);
                    }
                });
                return [total, frequencies, types];
            }
        )r  r   rF   rx   rU  r[   )rR   rh  r'  	freq_funcr  r  typesrZ  r[  rV  rY  s              rU   r)  &BaseQuerySet._item_frequencies_exec_js6  s    ,	Z "\\);U37::<@<41%))A,A&<@6<llnEndaaqE))nFELLNDA!U##q6Q;AAN #  A Fs   'C.C"c           	      d   / nU R                   R                  S   (       a3  U R                   R                   Vs/ s H  n[        U5      PM     snSS n/ nU HW  nUR	                  S5      n SR                  S U R                   R                  U5       5       5      nUR                  U5        MY     U$ s  snf ! [         ak  nSnU HO  n	 SR                  S U	R                  U5       5       5      n
UR                  U
5        Sn  O! [         a     MM  f = f   U(       d  Ue SnAM  SnAff = f)	z0Translate fields' paths to their db equivalents.r*   r#   Nr   c              3   h   #    U  H(  n[        U[        5      (       a  UOUR                  v   M*     g 7fr   r[   r   r  .0rv  s     rU   	<genexpr>3BaseQuerySet._fields_to_dbfields.<locals>.<genexpr>  s,      !F $As++A;F   02Fc              3   h   #    U  H(  n[        U[        5      (       a  UOUR                  v   M*     g 7fr   rc  rd  s     rU   rf  rg    s,      ,%F ",As!3!3AC%Frh  T)	r0   rE   rH   r   rm  r  r  r  r   )rR   rt  
subclassesr  db_field_pathsrh  r  r   foundsubdocsubfields              rU   rj   BaseQuerySet._fields_to_dbfieldsu  s6   
>> 3437>>3M3MN3Ma,q/3MNqrRJE++c*K !!^^99+F!  %%e, 8 ? O   )F	#&88 ,%+%9%9+%F, $ '--h7 $&  ) I #sB   B5-AB::
D/D*:DD*
D	D*D	D**D/c                 v   / nU H  nU(       d  M  US:X  a  UR                  SSS045        M)  [        R                  nUS   S:X  a  [        R                  nUS   S;   a  USS	 nUR	                  S
S5      n U R
                  R                  U5      nUR                  X445        M     U$ ! [         a     N$f = f)zGiven a list of MongoEngine-style sort keys, return a list
of sorting tuples that can be applied to a PyMongo cursor. For
example:

>>> qs._get_order_by(['-last_name', 'first_name'])
[('last_name', -1), ('first_name', 1)]
z$text_scorer:  r8  r9  r   -)rq  +r#   Nr  r   )r  r   	ASCENDING
DESCENDINGr  r0   r  	Exception)rR   r  key_listr|   	directions        rU   r  BaseQuerySet._get_order_by  s     Cm#+0F GH))I1v}#..	1v#!"g++dC(Cnn::3?
 OOS,-- 0   s   8B++
B87B8c                     S nU R                    Vs/ s H
  o2" X5      PM     nn[        U5      S:X  a  US   $ [        U5      $ s  snf )Nc                 P    UR                  S5      nU H  n[        X5      n M     U $ )Nr  )rm  rH  )objrc  chunkschunks       rU   lookup(BaseQuerySet._get_scalar.<locals>.lookup  s)    ZZ%Fc)  JrX   r#   r   )r>   rG   r  )rR   r   r~  r
  r  s        rU   ry   BaseQuerySet._get_scalar  sH    	 )-51s5t9>7NT{	 6s   Ac                 |   ^  U 4S jnU 4S jn[         R                  " SX!5      n[         R                  " SX15      nU$ )zWhen fields are specified with [~fieldname] syntax, where
*fieldname* is the Python name of a field, *fieldname* will be
substituted for the MongoDB name of the field (specified using the
:attr:`name` keyword argument in a field's constructor).
c                    > U R                  S5      R                  S5      nTR                  R                  U5      nSUS   R                  -  $ )Nr#   r   z["%s"]r/   )r  rm  r0   r  r  )r   r  rt  rR   s      rU   	field_sub.BaseQuerySet._sub_js_fields.<locals>.field_sub  sD    Q--c2J^^11*=FfRj1111rX   c                    > U R                  S5      R                  S5      nTR                  R                  U5      nSR	                  U Vs/ s H  o3R
                  PM     sn5      $ s  snf )Nr#   r   )r  rm  r0   r  r  r  )r   r  rt  rv  rR   s       rU   field_path_sub3BaseQuerySet._sub_js_fields.<locals>.field_path_sub  sR    Q--c2J^^11*=F888AZZ8998s   A(z\[\s*~([A-z_][A-z_0-9.]+?)\s*\]z#\{\{\s*~([A-z_][A-z_0-9.]+?)\s*\}\})r   sub)rR   r  r  r  s   `   rU   r  BaseQuerySet._sub_js_fields  s6    	2	: vv8)Jvv<nSrX   c                     U R                  5       nUR                  n[        XA5      " U5        [        USU-   U5        U$ )zkCall a particular method on the PyMongo cursor call a particular chainable method
with the provided value.
r  )r\   ru   rH  rI  )rR   method_namerM  r`   r  s        rU   r  BaseQuerySet._chainable_method  sC     ::< !! 	$S) 	#+S1rX   )__auto_dereference__dereferencer:   r@   rN   r4   rM   r1   rP   rI   r0   rQ   rL   r=   rJ   r6   rO   r2   r?   r7   r3   r<   r;   r>   rA   rB   rK   r8   r9   r5   r   )NT)TNN)F)NFN)FTNNFN)NN)FNFN)FFFFN)r#   )NNN)FT)Ur   
__module____qualname____firstlineno____doc__rV   ra   rj   ro   r}   r   r   r   r   r   r   rF   r   r   r   r   r   rn   r  r  r.  r  r   r:  r=  rC  r\   r@  rR  r   r   r   r   r_  rk  rw  r|  rt  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r$  r*  r.  r1  propertyr   r&  ru   rE  r   rQ  rs   rQ  r(  r)  rj  r  ry   r  r  __static_attributes__rZ   rX   rU   r   r   2   sP   0d8"
',?\";
 /:
8@
 NR\5|&PY,z J=X@  
H Pd52
LV/bD"(4$8t+$%$8t
 '+ %N7&	
 .$	9CE
0Ih KOxt'CR44J2( $ $  6 8  8 t ! ! " "
 8 80d=~#J!F2rX   r   )7rf   r  r   r"  collections.abcr   r   pymongo.errorsbsonr   r   	bson.coder   pymongo.collectionr   pymongo.commonr   pymongo.read_concernr	   mongoenginer
   mongoengine.baser   mongoengine.commonr   mongoengine.connectionr   mongoengine.context_managersr   r   r   r   mongoengine.errorsr   r   r   r   r   mongoengine.pymongo_supportr   r   mongoengine.querysetr   mongoengine.queryset.field_listr   mongoengine.queryset.visitorr   r   __all__r   r   r    r!   r"   r   rZ   rX   rU   <module>r     s      	  #     - 3 ,  ) , )   + : 1
N 


A ArX   