o xgI@sdZddlZddlZddlZddlmZddlZddlmZddl m Z ddl m Z m Z mZmZmZmZddlmZmZmZmZddlmZdd lmZdd lmZmZmZmZm Z m!Z!dd l"m#Z#m$Z$dd l%m&Z&m'Z'dd l(m)Z)m*Z*ddl+m,Z,m-Z-ddl.m/Z/ddl0m1Z1m2Z2dZ3dZ4GdddZ5Gddde5Z6Gddde5Z7Gddde5Z8Gddde8Z9Gddde5Z:Gdd d Z;Gd!d"d"e<Z=Gd#d$d$e=d%Z>Gd&d'd'Z?Gd(d)d)Z@d6d*d+ZAd,d-ZBd.d/ZCd0d1ZDGd2d3d3ZEd4d5ZFdS)7zM The main QuerySet implementation. This provides the public API for the ORM. N)chain)settings) exceptions)DJANGO_VERSION_PICKLE_KEYIntegrityErrorNotSupportedError connectionsrouter transaction) AutoField DateField DateTimeFieldsql LOOKUP_SEP) Collector)Case ExpressionFRefValueWhen)CastTrunc)FilteredRelationQ)CURSORGET_ITERATOR_CHUNK_SIZE)create_namedtuple_classresolve_callables)timezone)cached_property partitionc@seZdZdefddZdS) BaseIterableFcCs||_||_||_dSN)queryset chunked_fetch chunk_size)selfr'r(r)r+8/usr/lib/python3/dist-packages/django/db/models/query.py__init__$s zBaseIterable.__init__N)__name__ __module__ __qualname__rr-r+r+r+r,r%#sr%c@eZdZdZddZdS) ModelIterablez3Iterable that yields a model instance for each row.c #sb|jj}jj|d}|j|j|jd}|j|j|j }}}|d}|d}|d|dd} } dd || | D} t |||} fd d j D} | |D]W}||| || | }| D]}|||qf|r| D] \}}t||||qu| D]&\}}}||rq||}z||}Wn tyYqwt||j|q|VqWdS) Nusingr(r)model select_fieldsrcSg|]}|djjqSrtargetattname.0fr+r+r, 9sz*ModelIterable.__iter__..cs2g|]\}|tjfddjDfqS)cs*g|]}|dkr jnjj|jqSr*)r>r6_meta get_field)r@ from_field)fieldr'r+r,rB=s z5ModelIterable.__iter__...)operator attrgetter from_fields)r@ related_objsr')rGr,rB<s )r'dbquery get_compiler execute_sqlr(r)select klass_infoannotation_col_mapget_related_populators_known_related_objectsitems results_iterfrom_dbpopulatesetattr is_cachedKeyErrorname)r*rMcompilerresultsrQrRrS model_clsr7model_fields_startmodel_fields_end init_listrelated_populatorsknown_related_objectsrowobj rel_populator attr_namecol_posrGrel_objs rel_getter rel_obj_idrel_objr+rLr,__iter__-sJ       zModelIterable.__iter__Nr.r/r0__doc__ror+r+r+r,r2*s r2c@r1)ValuesIterablezQ Iterable returned by QuerySet.values() that yields a dict for each row. c#sn|j}|j}||j}g|j|j|jtt}|j |j |j dD] fdd|DVq'dS)Nr5csi|] }||qSr+r+r@inamesrfr+r, nz+ValuesIterable.__iter__..) r'rNrOrM extra_select values_selectannotation_selectrangelenrWr(r))r*r'rNr^indexesr+rur,roas  zValuesIterable.__iter__Nrpr+r+r+r,rr\s rrc@r1)ValuesListIterableze Iterable returned by QuerySet.values_list(flat=False) that yields a tuple for each row. cs|jj}|j}jrNg|j|j|j}gjfdd|jD}||krNddt|Dt j fdd|D}t ||j |j |jdS|j d|j |jd S) Nc3s|] }|jvr|VqdSr&)_fieldsr?rLr+r, z.ValuesListIterable.__iter__..cSsi|]\}}||qSr+r+)r@idxr]r+r+r,rwsz/ValuesListIterable.__iter__..cg|]}|qSr+r+r?) index_mapr+r,rBz/ValuesListIterable.__iter__..r5T)tuple_expectedr(r))r'rNrOrMrryrzr{ enumeraterH itemgettermaprWr(r))r*rNr^rvfields rowfactoryr+)rr'r,rows( zValuesListIterable.__iter__Nrpr+r+r+r,rq rcs eZdZdZfddZZS)NamedValuesListIterablezj Iterable returned by QuerySet.values_list(named=True) that yields a namedtuple for each row. c#s`|j}|jr |j}n|j}g|j|j|j}t|}tj}t D]}|||Vq%dSr&) r'rrNryrzr{rtuple__new__superro)r*r'rvrN tuple_classnewrf __class__r+r,rosz NamedValuesListIterable.__iter__)r.r/r0rqro __classcell__r+r+rr,rsrc@r1)FlatValuesListIterablez] Iterable returned by QuerySet.values_list(flat=True) that yields single values. ccs<|j}|j|j}|j|j|jdD]}|dVqdS)Nr5r)r'rNrOrMrWr(r))r*r'r^rfr+r+r,ros  zFlatValuesListIterable.__iter__Nrpr+r+r+r,rrrc@sZeZdZdZdddZeddZejddZdd Zd e_ e eZd d Z d dZ ddZ ddZddZddZddZddZddZddZdd Zd!d"Zdd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zdd1d2Zdd3d4Zd e_dd5d6Z dd7d8Z!d9d:Z"d;d<Z#d=d>Z$d?d@Z%dAdBZ&dCdDZ'ddEdFdGdHZ(dIdJZ)d e)_d e)_ dKdLZ*d e*_dMdNZ+d e+_dOdPZ,d e,_d0e,_ dQdRZ-dSdTZ.ddUdVdWZ/ddYdZZ0d[d\Z1d]d^Z2d0d0d_d`daZ3ddcddZ4ddedfZ5dgdhZ6didjZ7dkdlZ8dmdnZ9dodpZ:dqdrZ;dsdtZdzd{Z?d|d}Z@dd~dZAddZBddZCddZDddZEdddZFddZGddZH  dddZIddZJddZKddZLddZMeddZNeddZOdddZPd eP_d0eP_ dddZQddZRddZSddZTddZUddZVddZWddZXd eX_ ddZYddZZe[ddZ\ddZ]dS)QuerySetz6Represent a lazy database lookup for a set of objects.NcCsh||_||_|p i|_|pt|j|_d|_d|_d|_d|_ d|_ i|_ t |_ d|_d|_d|_dS)NFr+)r6_db_hintsrQuery_query _result_cache_sticky_filter _for_write_prefetch_related_lookups_prefetch_donerUr2_iterable_classr_defer_next_filter_deferred_filter)r*r6rNr4hintsr+r+r,r-s  zQuerySet.__init__cCs,|jr|j\}}}||||d|_|jSr&)r_filter_or_exclude_inplacerr*negateargskwargsr+r+r,rNs  zQuerySet.querycCs|jrt|_||_dSr&)rzrrrr)r*valuer+r+r,rNs cCs"ddlm}||}d|_|S)Nr)ManagerT)django.db.models.managerr from_queryset_built_with_as_manager)clsrmanagerr+r+r, as_managers  zQuerySet.as_managerTcCsF|}|jD]\}}|dkrd|j|<q t|||j|<q |S)z$Don't populate the QuerySet's cache.rN)r__dict__rVcopydeepcopy)r*memorgkvr+r+r, __deepcopy__s  zQuerySet.__deepcopy__cCs|i|jttjiSr&) _fetch_allrrdjango __version__rCr+r+r, __getstate__szQuerySet.__getstate__cCsT|t}|r|tjkrtjd|tjftddntjdtdd|j|dS)NzTPickled queryset instance's Django version %s does not match the current version %s.) stacklevelz)listREPR_OUTPUT_SIZEr}rr.)r*datar+r+r,__repr__s zQuerySet.__repr__cC|t|jSr&rr}rrCr+r+r,__len__ zQuerySet.__len__cCr)a The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql.compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects. riterrrCr+r+r,ro s zQuerySet.__iter__cCrr&rboolrrCr+r+r,__bool__rzQuerySet.__bool__cCst|ttfstdt|jt|ts|dks6t|tr2|jdus(|jdkr2|jdus6|jdks6Jd|jdur@|j|St|try| }|jdurTt|j}nd}|jdurat|j}nd}|j |||j rwt |dd|j S|S| }|j ||d||jdS)z2Retrieve an item or slice from the set of results.z4QuerySet indices must be integers or slices, not %s.rNz#Negative indexing is not supported.r9) isinstanceintslice TypeErrortyper.startstopr_chainrN set_limitssteprr)r*rqsrrr+r+r, __getitem__s:        zQuerySet.__getitem__cOs|Sr&r+)rrrr+r+r,__class_getitem__@szQuerySet.__class_getitem__cCsN||t|tr |St|tr|S|}|||j|jtj|Sr&) _merge_sanity_checkr EmptyQuerySetr_merge_known_related_objectsrNcombinerAND)r*othercombinedr+r+r,__and__Cs    zQuerySet.__and__cCs||t|tr |St|tr|S|jr|n |jjj|dd}| }| ||js>|jjj|dd}|j |jt j |S)Npkpk__in)rrrrN can_filterr6 _base_managerfiltervaluesrrrrOR)r*rrNrr+r+r,__or__Ns   $  zQuerySet.__or__ccs|j|||dEdHdS)Nr5)r)r*use_chunked_fetchr)r+r+r, _iterator`szQuerySet._iteratorcCs0|dkrtdt|jjd }|||S)zc An iterator over the results from applying this QuerySet to the database. rz%Chunk size must be strictly positive.DISABLE_SERVER_SIDE_CURSORS) ValueErrorrrM settings_dictrr)r*r)rr+r+r,iteratorcs zQuerySet.iteratorc Os|jjrtd|jg||Rdd|D]}z|jWn ttfy,tdw|||j<q|j}| D]<\}}|j ||dd|j |}|j sVtd|| D]}|j rwt|trw|j|vrw|j} td|j| | fqZq<||j|S) z Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias. z/aggregate() + distinct(fields) not implemented. aggregate method_namez#Complex aggregates require an aliasT) is_summaryz!%s is not an aggregate expressionz-Cannot compute %s('%s'): '%s' is an aggregate)rNdistinct_fieldsNotImplementedError _validate_values_are_expressionsr default_aliasAttributeErrorrrrVadd_annotation annotationscontains_aggregateget_source_expressionsrrrefsr FieldErrorr]get_aggregationrM) r*rrargrNaliasaggregate_expr annotationexprr]r+r+r,rms6       zQuerySet.aggregatecCs$|jdur t|jS|jj|jdS)z Perform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls. Nr3)rr}rN get_countrMrCr+r+r,counts  zQuerySet.countcOs|jjr|s|rtd|jj|jjr|n|j|i|}|jr-|jjs-|}d}|jjr:t |j j j rCt }|jj|dt|}|dkrP|jdS|s]|jd|jjj|jd|jjj|rk||krp|fd|df) zl Perform the query and return a single object matching the given keyword arguments. zCCalling QuerySet.get(...) with filters after %s() is not supported.Nhighr9rz!%s matching query does not exist.z2get() returned more than one %s -- it returned %s!z more than %s)rN combinatorrrrrrorder_byselect_for_updaterrMfeatures%supports_select_for_update_with_limitMAX_GET_RESULTSrr}rr6 DoesNotExistrD object_nameMultipleObjectsReturned)r*rrclonelimitnumr+r+r,rs>   z QuerySet.getcKs*|jdi|}d|_|jd|jd|S)z Create a new object with the given kwargs, saving it to the database and returning the created object. T) force_insertr4Nr+)r6rsaverMr*rrgr+r+r,createszQuerySet.createcCs4|D]}|jdur|jj||_|jddqdS)N bulk_create)operation_name)rrDget_pk_value_on_save _prepare_related_fields_for_save)r*objsrgr+r+r,_prepare_for_bulk_creates  z!QuerySet._prepare_for_bulk_createFcCs|dus |dks J|jjD]}|jj|jjjurtdq|s$|Sd|_t|j}|jj}|j}t |}| |t j |jddt dd|\}} |r|j||||d } t|| D]\} } t| |jD]\} }||jkrxt| |j| qhq^|D] } d| j_|j| j_q|| rd d |D}|j| |||d } |jjr|st| t| ksJt| | D]'\}} t| |jD] \} }t||j| qd|j_|j|j_qWd|SWd|S1swY|S) ab Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported. Nrz/Can't bulk create a multi-table inherited modelTFr4 savepointcSs |jduSr&r)or+r+r,s z&QuerySet.bulk_create..ignore_conflictscSg|] }t|ts|qSr+)rr r?r+r+r,rBrxz(QuerySet.bulk_create..)r6rDget_parent_listconcrete_modelrrrrMconcrete_fieldsrr(r atomicr"_batched_insertzipdb_returning_fieldsrrZr>_stateaddingr can_return_rows_from_bulk_insertr})r*r' batch_sizer/parent connectionoptsr objs_with_pkobjs_without_pkreturned_columns obj_with_pkr_resultrGobj_without_pkr+r+r,r#s`        zQuerySet.bulk_createc sdur dkr td|stdttddDr#tdfdd |D}td d|Dr9td td d|DrFtd sJdStjjddg|}r_t|n|tjjj }fddt dt D}g}|D]K}i} |D]8} g} |D]} t | | j } t| tst| | d} | t| j| dqt| d| i}|rt|| d}|| | j <q|dd |D| fq|tjjdd|D]\}} j|djdi| qWddS1swYdS)zW Update the given fields in each of the given objects in the database. Nrz&Batch size must be a positive integer.z+Field names must be given to bulk_update().css|]}|jduVqdSr&r+r@rgr+r+r,rsz'QuerySet.bulk_update..z6All bulk_update() objects must have a primary key set.csg|] }jj|qSr+)r6rDrE)r@r]rCr+r,rBrxz(QuerySet.bulk_update..css|] }|j p |jVqdSr&)concrete many_to_manyr?r+r+r,rrz4bulk_update() can only be used with concrete fields.cs|]}|jVqdSr&) primary_keyr?r+r+r,rz5bulk_update() cannot be used with primary key fields.rc3s |] }||VqdSr&r+rsr;r'r+r,r&s output_field)rthenrMcSg|]}|jqSr+r+rEr+r+r,rB5Fr)rr+)rranyrrMopsbulk_batch_sizeminrrequires_casted_case_in_updatesr|r}getattrr>rrrappendrrrrr r4rr)r*r'rr;max_batch_sizerequires_castingbatchesupdates batch_objs update_kwargsrGwhen_statementsrgattrcase_statementpksr+)r;r'r*r, bulk_updatesL       "zQuerySet.bulk_updatecKsd|_z |jdi|dfWS|jjyq|j|fi|}z.tj|jdtt |}|j di|dfWdWYS1sFwYWYdSt ypz|jdi|dfWYYS|jjyoYwww)z Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. TFr3Nr+) rrr6r_extract_model_paramsr r4rMdictrr"r)r*defaultsrparamsr+r+r, get_or_create;s& . zQuerySet.get_or_createcKs|pi}d|_tj|jd;|j|fi|\}}|r)||fWdSt|D] \}}t|||q-|j|jdWd|dfS1sLwY|dfS)z Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Return a tuple (object, created), where created is a boolean specifying whether an object was created. Tr3NF) rr r4rMrrgrrZr )r*rerrgcreatedrrr+r+r,update_or_createTs   zQuerySet.update_or_createc Ks|pi}dd|D}|||jjj}g}|D]%}z |jj|Wqtjy@||vr9t|j|j s>| |Yqw|rTt d|jjj d t|f|S)z Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create(). cSsi|] \}}t|vr||qSr+r)r@rrr+r+r,rwnz2QuerySet._extract_model_params..z)Invalid field name(s) for model %s: '%s'.z', ')rVrr6rD_property_namesrErFieldDoesNotExistrVfsetrWrrjoinsorted)r*rerrfproperty_namesinvalid_paramsparamr+r+r,rchs*    zQuerySet._extract_model_paramscGs|r|}nt|jjd}|rt|ttfs|f}|dur td|jjr(Jd| }|jj dd|jj dd|jj || S) zy Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by. get_latest_byNzmearliest() and latest() require either fields as positional arguments or 'get_latest_by' in the model's Meta.z2Cannot change a query once a slice has been taken.r9rTforce)rVr6rDrrrrrN is_slicedrrclear_ordering add_orderingr)r*rrrgr+r+r, _earliests"  zQuerySet._earliestcGs |j|Sr&)ryr*rr+r+r,earliest zQuerySet.earliestcGs|j|Sr&)reverseryrzr+r+r,latestszQuerySet.latestcCs,|jr|n|dddD]}|SdS)z@Return the first object of a query or None if no match is found.rNr9)orderedrr*rgr+r+r,firsts zQuerySet.firstcCs0|jr|n|dddD]}|SdS)z?Return the last object of a query or None if no match is found.z-pkNr9)rr}rrr+r+r,lasts$z QuerySet.lastr field_namec s|jjrJd|jj}dd|jD}dkr/|js/|vr/|jjfkr/td|dur|s7iSd }t |j j j }t|}|ru|t|krud}td t||D]}||||} |t|jdi|| i7}qYn|jdi||i}n|}fd d |DS) z Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet. z+Cannot use 'limit' or 'offset' with in_bulkcSs$g|]}t|jdkr|jdqS)r9r)r}r)r@ constraintr+r+r,rBs z$QuerySet.in_bulk..rz;in_bulk()'s field_name must be a unique field but %r isn't.Nz{}__inr+rcsi|]}t||qSr+)rVrErr+r,rwz$QuerySet.in_bulk..)rNrvr6rDtotal_unique_constraintsrEuniquerrformatrrMrmax_query_paramsrr}r|rrr) r*id_listrr> unique_fields filter_keyr;roffsetbatchr+rr,in_bulks8    "zQuerySet.in_bulkcCs|d|jjr Jd|jjs|jjrtd|jdur"td|}d|_d|j_ d|j_ |jj ddt |j d }|||\}}d|_||fS) z+Delete the records in the current QuerySet.deletez+Cannot use 'limit' or 'offset' with delete.z'Cannot call delete() after .distinct().Nz6Cannot call delete() after .values() or .values_list()TFrtr3)_not_support_combined_queriesrNrvdistinctrrrrrrselect_relatedrwrrMcollectrr)r* del_query collectordeleted _rows_countr+r+r,rs$      zQuerySet.deletecCsT|j}tj|_||t}|r(| |jWdS1s#wYdS)z Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades. Nr) rNrr DeleteQueryrrOrPrrowcount)r*r4rNcursorr+r+r, _raw_deletes  zQuerySet._raw_deletecKs|d|jjr Jdd|_|jtj}||i|_t j |j d| |j  t}Wdn1s:wYd|_|S)z~ Update all elements in the current QuerySet, setting all the given fields to the appropriate values. r2Cannot update a query once a slice has been taken.Tr3N)rrNrvrrr UpdateQueryadd_update_valuesrr mark_for_rollback_on_errorrMrOrPrr)r*rrNrowsr+r+r,rs   zQuerySet.updatecCsF|jjrJd|jtj}||i|_d|_||j  t S)a A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). rN) rNrvrrradd_update_fieldsrrrOrMrPr)r*rrNr+r+r,_updates  zQuerySet._updatecCs$|jdur |jj|jdSt|jS)Nr3)rrN has_resultsrMrrCr+r+r,exists&s  zQuerySet.existscCt|jg|jRd|_dSNTprefetch_related_objectsrrrrCr+r+r,_prefetch_related_objects+s z"QuerySet._prefetch_related_objects)rcKs|jjd|j|d|S)N)r4rr+)rNexplainrM)r*roptionsr+r+r,r0szQuerySet.explainr+cCs6|dur|j}t||j|||d}|jdd|_|S)N)r6rf translationsr4)rM RawQuerySetr6r)r* raw_queryrfrr4rr+r+r,raw7s z QuerySet.rawcOs2|}|r|jdi|}||_|j||S)Nr+)rannotaterrN set_valuesr*r expressionsrr+r+r,_values>s  zQuerySet._valuescOs&|t|7}|j|i|}t|_|Sr&)rrrrrrr+r+r,rFs zQuerySet.values)flatnamedc Gs|r|rtd|rt|dkrtddd|D}g}i}d}|D]1}t|drOt|d|jj} | t|} |d7}| |vrDnq5||| <|| q#||q#|j |i|} |rdt | _ | S|rkt | _ | St | _ | S)Nz*'flat' and 'named' can't be used together.r9zH'flat' is not valid when values_list is called with more than one field.cSsh|] }t|ds|qS)resolve_expressionhasattrr?r+r+r, Rrxz'QuerySet.values_list..rr)rr}rrVrr.lowerstrrWrrrrr) r*rrr field_namesrrcounterrGfield_id_prefixfield_idrr+r+r, values_listLs<    zQuerySet.values_listASCcCsp|dvsJd|dvsJd|jt||tdt|djddd jd d |d kr3d dSddS)z Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'. )yearmonthweekdayz8'kind' must be one of 'year', 'month', 'week', or 'day'.rDESC''order' must be either 'ASC' or 'DESC'.rL) datefield plain_fieldrTrFplain_field__isnullr-)rrr rrrrr)r*rkindorderr+r+r,datesks&  zQuerySet.datescCs|dvsJd|dvsJdtjr|durt}nd}|jt||t||dt|djdd d  j d d  |d krCddSddS)z Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. )rrrrhourminutesecondzT'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'.rrN)rMtzinfois_dst) datetimefieldrrTrFrrrr) rUSE_TZr get_current_timezonerrr rrrrr)r*rrrrrr+r+r, datetimes{s<      zQuerySet.datetimescCs|}|j|S)zReturn an empty QuerySet.)rrN set_emptyr*rr+r+r,nones z QuerySet.nonecCs|S)z Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. )rrCr+r+r,allsz QuerySet.allcO|d|d||S)za Return a new QuerySet instance with the args ANDed to the existing set. rFr_filter_or_excluder*rrr+r+r,r zQuerySet.filtercOr)zc Return a new QuerySet instance with NOT (args) ANDed to the existing set. excludeTrrr+r+r,rrzQuerySet.excludecCsN|s|r |jjr Jd|}|jrd|_|||f|_|S|||||S)Nz2Cannot filter a query once a slice has been taken.F)rNrvrrrr)r*rrrrr+r+r,rs  zQuerySet._filter_or_excludecCs:|r|jt|i|dS|jt|i|dSr&)radd_qrrr+r+r,rsz#QuerySet._filter_or_exclude_inplacecCs2t|tr|}|j||S|jdd|dS)aB Return a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. Fr+)rr)rrrrNrr)r* filter_objrr+r+r,complex_filters  zQuerySet.complex_filter)rcGsR|}|jjdd|j|jftdd|D|j_||j_||j_|S)NTrtcsrHr&)rN)r@rr+r+r,rrJz-QuerySet._combinator_query..)rrNrw clear_limitsrcombined_queriesrcombinator_all)r*rrother_qsrr+r+r,_combinator_querys zQuerySet._combinator_querycGspt|tr,dd|D}|s|St|dkr|dS|djdg|ddRd|iS|jdg|Rd|iS)NcSr0r+)rr)r@qr+r+r,rBrxz"QuerySet.union..r9runionr)rrr}r)r*rrrr+r+r,rs  $zQuerySet.unioncGs<t|tr|S|D] }t|tr|Sq |jdg|RS)N intersectionrrr)r*rrr+r+r,rs  zQuerySet.intersectioncGs t|tr|S|jdg|RS)N differencer)r*rr+r+r,rs zQuerySet.differencecCsJ|r|rtd|}d|_d|j_||j_||j_||j_||j_|S)zi Return a new QuerySet instance that will select objects with a FOR UPDATE lock. z2The nowait option cannot be used with skip_locked.T) rrrrNrselect_for_update_nowaitselect_for_update_skip_lockedselect_for_update_ofselect_for_no_key_update)r*nowait skip_lockedofno_keyrgr+r+r,rszQuerySet.select_for_updatecGsX|d|jdurtd|}|dkrd|j_|S|r&|j||Sd|j_|S)a Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list. rNz>Cannot call select_related() after .values() or .values_list()r&FT)rrrrrNradd_select_related)r*rrgr+r+r,rs  zQuerySet.select_relatedcGsr|d|}|dkrd|_|S|D]}t|tr|j}|tdd}||jj vr0t dq|j||_|S)aN Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list. prefetch_relatedr&r+r9rz:prefetch_related() is not supported with FilteredRelation.) rrrrPrefetch prefetch_tosplitrrN_filtered_relationsr)r*lookupsrlookupr+r+r,r&s     zQuerySet.prefetch_relatedcO|d|j||ddS)z Return a query set in which the returned objects have been annotated with extra data or aggregations. rTrQr _annotaterr+r+r,r=s zQuerySet.annotatecOr)zW Return a query set with added aliases for extra data or aggregations. r Frrrr+r+r,r Es zQuerySet.aliasc CsJ|j|t|ddi}|D]!}z|j|vr td|jWn ty,tdw|||j<q|||}|j}|durSt t dd|j j D}|D]%\}} ||vretd|t| trr|j| |qW|jj| |d|d qW|jjD]\}} ||vr| jr|jdurd |j_|S|j|Sq|S) NrrzQThe named annotation '%s' conflicts with the default name for another annotation.z$Complex annotations require an aliascss.|]}t|dr|j|jfn|jfVqdS)r>N)rr]r>)r@rGr+r+r,r^s  z%QuerySet._annotate..z8The annotation '%s' conflicts with a field on the model.F)rrQT)rrrrrrrrrsetr from_iterabler6rD get_fieldsrVrrrNadd_filtered_relationrrrgroup_by set_group_by) r*rrrQrr rrvr r r+r+r,r LsR          zQuerySet._annotatecGs8|jjrJd|}|jjddd|jj||S)z9Return a new QuerySet instance with the ordering changed.z3Cannot reorder a query once a slice has been taken.TF)ru clear_default)rNrvrrwrxr*rrgr+r+r,rws  zQuerySet.order_bycGs2|d|jjr Jd|}|jj||S)zX Return a new QuerySet instance that will select only distinct results. rz:Cannot create distinct fields once a slice has been taken.)rrNrvradd_distinct_fieldsrr+r+r,rs   zQuerySet.distinctcCs<|d|jjr Jd|}|j|||||||S)z%Add extra SQL fragments to the query.extraz1Cannot change a query once a slice has been taken)rrNrvr add_extra)r*rQwhererftablesr select_paramsrr+r+r,rs  zQuerySet.extracCs*|jjrtd|}|jj |j_|S)z%Reverse the ordering of the QuerySet.z3Cannot reverse a query once a slice has been taken.)rNrvrrstandard_orderingrr+r+r,r}s zQuerySet.reversecGsJ|d|jdurtd|}|dkr|j|S|j||S)a% Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals. deferNz5Cannot call defer() after .values() or .values_list()r&)rrrrrNclear_deferred_loadingadd_deferred_loading)r*rrr+r+r,rs    zQuerySet.defercGsr|d|jdurtd|dkrtd|D]}|tdd}||jjvr,tdq|}|j ||S) z Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. onlyNz4Cannot call only() after .values() or .values_list()r&z*Cannot pass None as an argument to only().r9rz.only() is not supported with FilteredRelation.) rrrrrrNrrradd_immediate_loading)r*rrGrr+r+r,rs    z QuerySet.onlycCs|}||_|S)z;Select which database this QuerySet should execute against.)rr)r*r rr+r+r,r4szQuerySet.usingcCsFt|trdS|jjs|jjrdS|jjr!|jjr!|jjs!dSdS)z Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty). TF) rrrNextra_order_byrdefault_orderingget_metaorderingrrCr+r+r,rs  zQuerySet.orderedcCs>|jr|jptj|jfi|jS|jptj|jfi|jSz7Return the database used if this query is executed now.)rrr db_for_writer6r db_for_readrCr+r+r,rMsz QuerySet.dbcCsFd|_|dur |j}tj|j|d}|j|||d|j|d|S)z Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. TNr.)rr3)rrMr InsertQueryr6 insert_valuesrOrP)r*r'rreturning_fieldsrr4r/rNr+r+r,_inserts zQuerySet._insertc s|r t|jjjs tdt|jj}t||d}r#t|n|g}t|jjj }fddt dt DD]"} |rV|sV| |j | ||j|jjj|dq>|j | ||j|dq>|S)zU Helper method for bulk_create() to insert objs one batch at a time. z:This database backend does not support ignoring conflicts.r9csg|] }||qSr+r+rsrKr+r,rBsz,QuerySet._batched_insert..r)rr4r'r/)rr4r/)rrMrsupports_ignore_conflictsrrRmaxrSrTr:r|r}extendr(r6rDr7) r*r'rr;r/rRrX inserted_rows bulk_returnitemr+rKr,r5s  $ zQuerySet._batched_insertcKs,|}|jrd|j_d|_|j||S)zc Return a copy of the current QuerySet that's ready for another operation. TF)_clonerrNfilter_is_stickyrrr!r+r+r,rs  zQuerySet._chaincCsZ|j|j|j|j|jd}|j|_|j|_|jdd|_|j |_ |j |_ |j |_ |S)zi Return a copy of the current QuerySet. A lightweight alternative to deepcopy(). )r6rNr4rN) rr6rNrrrrrrrUrrr*cr+r+r,r/szQuerySet._clonecCs:|jdur t|||_|jr|js|dSdSdSr&)rrrrrrrCr+r+r,r*s   zQuerySet._fetch_allcCs d|_|S)a  Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. T)rrCr+r+r,_next_is_sticky0s zQuerySet._next_is_stickycCsj|jdur1t|jjt|jjks)t|jjt|jjks)t|jjt|jjkr3td|jjdSdS)z.Check that two QuerySet classes may be merged.Nz?Merging '%s' classes must involve the same values in each case.) rr rNrzryr{rrr.r*rr+r+r,r>s zQuerySet._merge_sanity_checkcCs,|jD]\}}|j|i|qdS)zX Keep track of all known related objects from either QuerySet instance. N)rUrV setdefaultr)r*rrGobjectsr+r+r,rIsz%QuerySet._merge_known_related_objectscOs:|jrt|jdkrtd|jj|i|}|j|_|S)Nr9z0Cannot use multi-field values as a filter value.)rr}rrNrr)r*rrrNr+r+r,rPs zQuerySet.resolve_expressioncKs|j|dS)z} Update hinting information for use by routers. Add new key/values or overwrite existing key/values. N)rr)r*rr+r+r, _add_hintsZszQuerySet._add_hintscCs |jS)z Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False. )rN has_filtersrCr+r+r, _has_filtersas zQuerySet._has_filterscCs0tdd|D}|rtd|d|fdS)Ncss"|] }t|dst|VqdS)rN)rr)r@r r+r+r,rks z.z-QuerySet.%s() received non-expression(s): %s.z, )rorrn)rr invalid_argsr+r+r,risz)QuerySet._validate_values_are_expressionscCs |jjrtd||jjfdS)Nz2Calling QuerySet.%s() after %s() is not supported.)rNrr)r*r$r+r+r,rts z&QuerySet._not_support_combined_queries)NNNN)r)NFr&)r+NN)r)rNN)FFr+F)T)NNNNNN)NFNF)F)^r.r/r0rqr-propertyrNsetterr queryset_only classmethodrrrrrrorrrrrrrrrrr"r(r#rb alters_datargrircryr{r~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr r rrrr}rrr4rrMr(r5rr/rr3rrrr7r9 staticmethodrrr+r+r+r,rs    !   $    @*  '          +             rc@seZdZddZdS)InstanceCheckMetacCst|to |jSr&)rrrNis_empty)r*instancer+r+r,__instancecheck__}sz#InstanceCheckMeta.__instancecheck__N)r.r/r0rDr+r+r+r,rA|s rAc@r1)rzz Marker class to checking if a queryset is empty by .none(): isinstance(qs.none(), EmptyQuerySet) -> True cOstd)Nz#EmptyQuerySet can't be instantiated)rrr+r+r,r-szEmptyQuerySet.__init__N)r.r/r0rqr-r+r+r+r,rrr) metaclassc@seZdZdZ  d$ddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZddZeddZddZed d!Zed"d#ZdS)%rzo Provide an iterator which converts the results of raw SQL queries into annotated model instances. Nr+cCsZ||_||_||_|p i|_|ptj||j|d|_||_|p i|_ d|_ d|_ d|_ dS)N)rr4rfr+F) rr6rrrRawQueryrMrNrfrrrr)r*rr6rNrfrr4rr+r+r,r-s   zRawQuerySet.__init__csltjjjfddjjjD}fddtjD}fdd|D}dd|D}|||fS)z1Resolve the init field names and value positions.cs g|] }|jjvr|qSr+)columncolumnsr? converterr*r+r,rBs z8RawQuerySet.resolve_model_init_order..cs"g|] \}}|jvr||fqSr+) model_fields)r@posrGrCr+r,rBs csg|] }j|jqSr+)rHindexrGr?rIr+r,rBrjcSrOr+r>r?r+r+r,rBrP) rrM introspectionidentifier_converterr6rDrrrH)r*model_init_fieldsannotation_fieldsmodel_init_ordermodel_init_namesr+rIr,resolve_model_init_orders  z$RawQuerySet.resolve_model_init_ordercGs*|}|dkr d|_|S|j||_|S)z#Same as QuerySet.prefetch_related()r&r+)r/r)r*rrr+r+r,rs  zRawQuerySet.prefetch_relatedcCrrrrCr+r+r,rs z%RawQuerySet._prefetch_related_objectsc Cs:|j|j|j|j|j|j|j|jd}|jdd|_|S)zSame as QuerySet._clone())r6rNrfrr4rN) rrr6rNrfrrrrr1r+r+r,r/s  zRawQuerySet._clonecCs8|jdur t||_|jr|js|dSdSdSr&)rrrrrrrCr+r+r,rs   zRawQuerySet._fetch_allcCrr&rrCr+r+r,rrzRawQuerySet.__len__cCrr&rrCr+r+r,rrzRawQuerySet.__bool__cCrr&rrCr+r+r,rorzRawQuerySet.__iter__c #s>j}t|jdjt||}tj}zs\}}}jjj j |vr-t dj}fddj D}|dd|D} | rL||| }|D]&fdd|D} |||| } |rq|D] \} } t| | | qd| VqNWtjdrjjrjjdSdSdStjdrjjrjjwww)N SQLCompilerz&Raw query must include the primary keycsg|]}j|qSr+)rKr)r@r2rCr+r,rBrz(RawQuerySet.iterator..cSs$g|]}|r||jjjndqSr&)get_colr6rDdb_tabler?r+r+r,rBscrr+r+)r@rL)rr+r,rBrr)rMrrRr^rNrrUr6rDrr>rrlrHget_convertersapply_convertersrXrZrrclose)r*rMr^rNrTmodel_init_posrRr`r convertersmodel_init_valuesrCrGrLr+)r*rr,rs@      zRawQuerySet.iteratorcCsd|jj|jfS)Nz<%s: %s>)rr.rNrCr+r+r,rszRawQuerySet.__repr__cCs t||Sr&)r)r*rr+r+r,rs zRawQuerySet.__getitem__cCs|jp tj|jfi|jSr")rr r$r6rrCr+r+r,rMszRawQuerySet.dbcCs&t|j|j|jj|d|j|j|dS)z