3
gI                @   s  d Z ddlZddlZddlZddlmZ ddlZddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZmZmZmZm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 dZ3dZ4G dd dZ5G dd de5Z6G dd de5Z7G dd de5Z8G dd de8Z9G dd de5Z:G dd  d Z;G d!d" d"e<Z=G d#d$ d$e=d%Z>G d&d' d'Z?G d(d) d)Z@d6d*d+ZAd,d- ZBd.d/ ZCd0d1 ZDG d2d3 d3ZEd4d5 ZFdS )7zM
The main QuerySet implementation. This provides the public API for the ORM.
    N)chain)settings)
exceptions)DJANGO_VERSION_PICKLE_KEYIntegrityErrorNotSupportedErrorconnectionsroutertransaction)	AutoField	DateFieldDateTimeFieldsql)
LOOKUP_SEP)	Collector)Case
ExpressionFRefValueWhen)CastTrunc)FilteredRelationQ)CURSORGET_ITERATOR_CHUNK_SIZE)create_namedtuple_classresolve_callables)timezone)cached_property	partition      c               @   s   e Zd ZdefddZdS )BaseIterableFc             C   s   || _ || _|| _d S )N)querysetchunked_fetch
chunk_size)selfr%   r&   r'    r)   T/var/www/tester-filtro-web/env/lib/python3.6/site-packages/django/db/models/query.py__init__$   s    zBaseIterable.__init__N)__name__
__module____qualname__r   r+   r)   r)   r)   r*   r$   #   s   r$   c               @   s   e Zd ZdZdd ZdS )ModelIterablez3Iterable that yields a model instance for each row.c             #   s|  | j   j} jj|d}|j| j| jd}|j|j|j	  }}}|d }|d }|d |d
 d  }	}
dd ||	|
 D }t
|||} fd	d jj D }x|j|D ]}|j||||	|
 }x|D ]}|j|| qW |rx$|j D ]\}}t||||  qW x^|D ]V\}}}|j|r.q||}y|| }W n tk
rX   Y nX t||j| qW |V  qW d S )N)using)r&   r'   modelselect_fieldsr      c             S   s   g | ]}|d  j jqS )r   )targetattname).0fr)   r)   r*   
<listcomp>9   s   z*ModelIterable.__iter__.<locals>.<listcomp>c                s2   g | ]*\ } |t j fd d jD  fqS )c                s*   g | ]"}|d kr j njjj|j qS )r(   )r5   r1   _meta	get_field)r6   Z
from_field)fieldr%   r)   r*   r8   >   s   z5ModelIterable.__iter__.<locals>.<listcomp>.<listcomp>)operator
attrgetterZfrom_fields)r6   Zrelated_objs)r%   )r;   r*   r8   =   s   )r%   dbqueryget_compilerexecute_sqlr&   r'   select
klass_infoannotation_col_mapget_related_populators_known_related_objectsitemsresults_iterfrom_dbpopulatesetattr	is_cachedKeyErrorname)r(   r?   compilerresultsrC   rD   rE   	model_clsr2   Zmodel_fields_startZmodel_fields_end	init_listrelated_populatorsZknown_related_objectsrowobjZrel_populator	attr_nameZcol_posr;   Zrel_objsZ
rel_getterZ
rel_obj_idrel_objr)   )r%   r*   __iter__-   s>    

zModelIterable.__iter__N)r,   r-   r.   __doc__rY   r)   r)   r)   r*   r/   *   s   r/   c               @   s   e Zd ZdZdd ZdS )ValuesIterablezQ
    Iterable returned by QuerySet.values() that yields a dict for each row.
    c             #   sj   | j }|j}|j|j}|j|j|j tt }x0|j	| j
| jdD ] fdd|D V  qHW d S )N)r&   r'   c                s   i | ]}|  | qS r)   r)   )r6   i)namesrU   r)   r*   
<dictcomp>n   s    z+ValuesIterable.__iter__.<locals>.<dictcomp>)r%   r@   rA   r?   extra_selectvalues_selectannotation_selectrangelenrI   r&   r'   )r(   r%   r@   rP   Zindexesr)   )r]   rU   r*   rY   a   s    zValuesIterable.__iter__N)r,   r-   r.   rZ   rY   r)   r)   r)   r*   r[   \   s   r[   c               @   s   e Zd ZdZdd ZdS )ValuesListIterableze
    Iterable returned by QuerySet.values_list(flat=False) that yields a tuple
    for each row.
    c                s   | j j}|jj}jr|j|j|j}jfdd|jD }||krdd t|D  t	j
 fdd|D  }t||j| j| jdS |jd| j| jd	S )
Nc             3   s   | ]}| j kr|V  qd S )N)_fields)r6   r7   )r%   r)   r*   	<genexpr>   s    z.ValuesListIterable.__iter__.<locals>.<genexpr>c             S   s   i | ]\}}||qS r)   r)   )r6   idxrO   r)   r)   r*   r^      s    z/ValuesListIterable.__iter__.<locals>.<dictcomp>c                s   g | ]} | qS r)   r)   )r6   r7   )	index_mapr)   r*   r8      s    z/ValuesListIterable.__iter__.<locals>.<listcomp>)r&   r'   T)Ztuple_expectedr&   r'   )r%   r@   rA   r?   re   r_   r`   ra   	enumerater<   
itemgettermaprI   r&   r'   )r(   r@   rP   r]   fieldsZ
rowfactoryr)   )rh   r%   r*   rY   w   s    zValuesListIterable.__iter__N)r,   r-   r.   rZ   rY   r)   r)   r)   r*   rd   q   s   rd   c                   s    e Zd ZdZ fddZ  ZS )NamedValuesListIterablezj
    Iterable returned by QuerySet.values_list(named=True) that yields a
    namedtuple for each row.
    c             #   s\   | j }|jr|j}n|j}|j|j|j}t| }tj}xt	 j
 D ]}|||V  qDW d S )N)r%   re   r@   r_   r`   ra   r   tuple__new__superrY   )r(   r%   r]   r@   Ztuple_classnewrU   )	__class__r)   r*   rY      s    z NamedValuesListIterable.__iter__)r,   r-   r.   rZ   rY   __classcell__r)   r)   )rr   r*   rm      s   rm   c               @   s   e Zd ZdZdd ZdS )FlatValuesListIterablez]
    Iterable returned by QuerySet.values_list(flat=True) that yields single
    values.
    c             c   s>   | j }|jj|j}x$|j| j| jdD ]}|d V  q(W d S )N)r&   r'   r   )r%   r@   rA   r?   rI   r&   r'   )r(   r%   rP   rU   r)   r)   r*   rY      s    zFlatValuesListIterable.__iter__N)r,   r-   r.   rZ   rY   r)   r)   r)   r*   rt      s   rt   c               @   sd  e Zd ZdZdddZedd Zejdd Zdd	 Zd
e_	e
eZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zdd$d%Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zdd1d2Zdd3d4Zd
e_dd5d6Z dd7d8Z!d9d: Z"d;d< Z#d=d> Z$d?d@ Z%dAdB Z&dCdD Z'ddEdFdGdHZ(dIdJ Z)d
e)_d
e)_	dKdL Z*d
e*_dMdN Z+d
e+_dOdP Z,d
e,_d0e,_	dQdR Z-dSdT Z.ddUdVdWZ/f ddfdXdYZ0dZd[ Z1d\d] Z2d0d0d^d_d`Z3ddbdcZ4ddddeZ5dfdg Z6dhdi Z7djdk Z8dldm Z9dndo Z:dpdq Z;drds Z<d0dtdudvZ=d0dtdwdxZ>dydz Z?d{d| Z@d0d0f d0fd}d~ZAdd ZBdd ZCdd ZDdd ZEdddZFdd ZGdd ZHdddZIdd ZJdd ZKdd ZLdd ZMedd ZNedd ZOdddZPd
eP_d0eP_	dddZQdd ZRdd ZSdd ZTdd ZUdd ZVdd ZWdd ZXd
eX_	dd ZYdd ZZe[dd Z\dd Z]dS )QuerySetz6Represent a lazy database lookup for a set of objects.Nc             C   sh   || _ || _|pi | _|p$tj| j | _d | _d| _d| _f | _	d| _
i | _t| _d | _d| _d | _d S )NF)r1   _db_hintsr   ZQuery_query_result_cache_sticky_filter
_for_write_prefetch_related_lookups_prefetch_donerG   r/   _iterable_classre   _defer_next_filter_deferred_filter)r(   r1   r@   r0   hintsr)   r)   r*   r+      s    
zQuerySet.__init__c             C   s,   | j r&| j \}}}| j||| d | _ | jS )N)r   _filter_or_exclude_inplacerx   )r(   negateargskwargsr)   r)   r*   r@      s
    zQuerySet.queryc             C   s   |j rt| _|| _d S )N)r`   r[   r~   rx   )r(   valuer)   r)   r*   r@      s    c             C   s"   ddl m} |j|  }d|_|S )Nr   )ManagerT)Zdjango.db.models.managerr   Zfrom_querysetZ_built_with_as_manager)clsr   managerr)   r)   r*   
as_manager   s    zQuerySet.as_managerTc             C   sJ   | j  }x<| jj D ].\}}|dkr0d|j|< qtj|||j|< qW |S )z$Don't populate the QuerySet's cache.ry   N)rr   __dict__rH   copydeepcopy)r(   memorV   kvr)   r)   r*   __deepcopy__   s    zQuerySet.__deepcopy__c             C   s   | j   | jttjiS )N)
_fetch_allr   r   django__version__)r(   r)   r)   r*   __getstate__   s    zQuerySet.__getstate__c             C   sT   |j t}|r4|tjkrDtjd|tjf tdd ntjdtdd | jj| d S )NzTPickled queryset instance's Django version %s does not match the current version %s.   )
stacklevelz<Pickled queryset instance's Django version is not specified.)	getr   r   r   warningswarnRuntimeWarningr   update)r(   stateZpickled_versionr)   r)   r*   __setstate__   s    



zQuerySet.__setstate__c             C   s8   t | d td  }t|tkr(d|d< d| jj|f S )Nr3   z$...(remaining elements truncated)...z<%s %r>r>   )listREPR_OUTPUT_SIZErc   rr   r,   )r(   datar)   r)   r*   __repr__   s    zQuerySet.__repr__c             C   s   | j   t| jS )N)r   rc   ry   )r(   r)   r)   r*   __len__  s    zQuerySet.__len__c             C   s   | j   t| jS )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.
        )r   iterry   )r(   r)   r)   r*   rY   	  s    zQuerySet.__iter__c             C   s   | j   t| jS )N)r   boolry   )r(   r)   r)   r*   __bool__  s    zQuerySet.__bool__c             C   s   t |ttfs tdt|j t |t r4|dksnt |trf|jdksR|jdkrf|jdksn|jdksntd| j	dk	r| j	| S t |tr| j
 }|jdk	rt|j}nd}|jdk	rt|j}nd}|jj|| |jrt|dd|j S |S | j
 }|jj||d  |j  |j	d S )z2Retrieve an item or slice from the set of results.z4QuerySet indices must be integers or slices, not %s.r   Nz#Negative indexing is not supported.r3   )
isinstanceintslice	TypeErrortyper,   startstopAssertionErrorry   _chainr@   
set_limitsstepr   r   )r(   r   qsr   r   r)   r)   r*   __getitem__  s0    




zQuerySet.__getitem__c             O   s   | S )Nr)   )r   r   r   r)   r)   r*   __class_getitem__@  s    zQuerySet.__class_getitem__c             C   sN   | j | t|tr|S t| tr&| S | j }|j| |jj|jtj |S )N)	_merge_sanity_checkr   EmptyQuerySetr   _merge_known_related_objectsr@   combiner   AND)r(   othercombinedr)   r)   r*   __and__C  s    



zQuerySet.__and__c             C   s   | j | t| tr|S t|tr&| S | jj r4| n| jjj| jdd}|j	 }|j
| |jj s||jjj|jdd}|jj|jtj |S )Npk)pk__in)r   r   r   r@   
can_filterr1   Z_base_managerfiltervaluesr   r   r   r   OR)r(   r   r@   r   r)   r)   r*   __or__N  s    


$

zQuerySet.__or__c             c   s   | j | ||dE d H  d S )N)r&   r'   )r~   )r(   use_chunked_fetchr'   r)   r)   r*   	_iterator`  s    zQuerySet._iterator  c             C   s0   |dkrt dt| j jjd }| j||S )zc
        An iterator over the results from applying this QuerySet to the
        database.
        r   z%Chunk size must be strictly positive.ZDISABLE_SERVER_SIDE_CURSORS)
ValueErrorr   r?   Zsettings_dictr   r   )r(   r'   r   r)   r)   r*   iteratorc  s    zQuerySet.iteratorc       
      O   s  | j jrtd| j||j dd xB|D ]:}y
|j W n  ttfk
rZ   tdY nX |||j< q,W | j j }x|j	 D ]|\}}|j
||dd |j| }|jstd| xF|j D ]:}|jrt|tr|j|kr|j}	tjd|j|	|	f qW q~W |j| 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)r@   distinct_fieldsNotImplementedError _validate_values_are_expressionsr   default_aliasAttributeErrorr   r   rH   add_annotationannotationscontains_aggregateZget_source_expressionsr   r   refsr   
FieldErrorrO   Zget_aggregationr?   )
r(   r   r   argr@   aliasZaggregate_expr
annotationexprrO   r)   r)   r*   r   m  s,    



zQuerySet.aggregatec             C   s$   | j dk	rt| j S | jj| jdS )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.
        N)r0   )ry   rc   r@   Z	get_countr?   )r(   r)   r)   r*   count  s    

zQuerySet.countc             O   s   | j jr |s|r td| j j | j jr0| j n
| j||}| j j rX| j j rX|j }d}|j j stt	|j
 jjrt}|j j|d t|}|dkr|jd S |s| jjd| jjj | jjd| jjj| s||k r|n
d|d  f dS )	zl
        Perform the query and return a single object matching the given
        keyword arguments.
        zCCalling QuerySet.get(...) with filters after %s() is not supported.N)highr3   r   z!%s matching query does not exist.z2get() returned more than one %s -- it returned %s!zmore than %s)r@   
combinatorr   r   r   r   r   order_byselect_for_updater   r?   featuresZ%supports_select_for_update_with_limitMAX_GET_RESULTSr   rc   ry   r1   DoesNotExistr9   object_nameZMultipleObjectsReturned)r(   r   r   clonelimitnumr)   r)   r*   r     s,    
zQuerySet.getc             K   s&   | j f |}d| _|jd| jd |S )z
        Create a new object with the given kwargs, saving it to the database
        and returning the created object.
        T)Zforce_insertr0   )r1   r{   saver?   )r(   r   rV   r)   r)   r*   create  s    zQuerySet.createc             C   s8   x2|D ]*}|j d kr$|jj j||_ |jdd qW d S )Nbulk_create)operation_name)r   r9   Zget_pk_value_on_saveZ _prepare_related_fields_for_save)r(   objsrV   r)   r)   r*   _prepare_for_bulk_create  s    

z!QuerySet._prepare_for_bulk_createFc             C   s  |dks|dkst x.| jjj D ]}|jj| jjjk	r"tdq"W |sL|S d| _t| j }| jj}|j	}t
|}| j| tj| jdd@ tdd |\}}	|r&| j||||d	}
xHt||
D ]:\}}x0t||jD ] \}}||jkrt||j| qW qW x |D ]}d|j_| j|j_q
W |	rd
d |D }| j|	|||d	}
|jjrt| rtt|
t|	kstt xTt|	|
D ]F\}}x(t||jD ]\}}t||j| qW d|j_| j|j_qW W dQ R X |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.
        Nr   z/Can't bulk create a multi-table inherited modelTF)r0   	savepointc             S   s
   | j d kS )N)r   )or)   r)   r*   <lambda>  s    z&QuerySet.bulk_create.<locals>.<lambda>)ignore_conflictsc             S   s   g | ]}t |ts|qS r)   )r   r   )r6   r7   r)   r)   r*   r8     s    z(QuerySet.bulk_create.<locals>.<listcomp>)r   r1   r9   Zget_parent_listZconcrete_modelr   r{   r   r?   concrete_fieldsr   r   r
   atomicr!   _batched_insertzipdb_returning_fieldsr   rL   r5   _stateZaddingr    can_return_rows_from_bulk_insertrc   )r(   r   
batch_sizer   parent
connectionoptsrl   Zobjs_with_pkZobjs_without_pkZreturned_columnsZobj_with_pkrQ   resultr;   Zobj_without_pkr)   r)   r*   r     sH    



zQuerySet.bulk_createc                s   dk	r dk rt d|s$t dttdd D rFt dfdd	|D }td
d |D rrt dtdd |D rt dsdS tj jjddg| } rt |n| tj jj	} fddt
dt D }g }x|D ]}i }	x|D ]|}
g }xF|D ]>}t||
j}t|ts>t||
d}|jt|j|d qW t|d|
i}|rxt||
d}||	|
j< qW |jdd	 |D |	f qW tjjdd. x&|D ]\}}	j|djf |	 qW W dQ R X dS )zW
        Update the given fields in each of the given objects in the database.
        Nr   z&Batch size must be a positive integer.z+Field names must be given to bulk_update().c             s   s   | ]}|j d kV  qd S )N)r   )r6   rV   r)   r)   r*   rf     s    z'QuerySet.bulk_update.<locals>.<genexpr>z6All bulk_update() objects must have a primary key set.c                s   g | ]} j jj|qS r)   )r1   r9   r:   )r6   rO   )r(   r)   r*   r8     s    z(QuerySet.bulk_update.<locals>.<listcomp>c             s   s   | ]}|j  p|jV  qd S )N)ZconcreteZmany_to_many)r6   r7   r)   r)   r*   rf     s    z4bulk_update() can only be used with concrete fields.c             s   s   | ]}|j V  qd S )N)Zprimary_key)r6   r7   r)   r)   r*   rf     s    z5bulk_update() cannot be used with primary key fields.r   c             3   s   | ]}||   V  qd S )Nr)   )r6   r\   )r   r   r)   r*   rf   &  s    )output_field)r   Zthenr   c             S   s   g | ]
}|j qS r)   )r   )r6   rV   r)   r)   r*   r8   5  s    F)r0   r   )r   )r   rn   anyr   r?   opsbulk_batch_sizeminr   Zrequires_casted_case_in_updatesrb   rc   getattrr5   r   r   r   appendr   r   r   r   r
   r   r   r   )r(   r   rl   r   max_batch_sizeZrequires_castingZbatchesZupdatesZ
batch_objsZupdate_kwargsr;   Zwhen_statementsrV   attrZcase_statementZpksr)   )r   r   r(   r*   bulk_update  sH     


zQuerySet.bulk_updatec             K   s   d| _ y| jf |dfS  | jjk
r   | j|f|}y6tj| jd tt	|}| j
f |dfS Q R X W n@ tk
r   y| jf |dfS  | jjk
r   Y nX  Y nX Y nX dS )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.
        TF)r0   N)r{   r   r1   r   _extract_model_paramsr
   r   r?   dictr   r   r   )r(   defaultsr   paramsr)   r)   r*   get_or_create;  s    zQuerySet.get_or_createc             K   s   |pi }d| _ tj| jdX | j j|f|\}}|r@||fS x t|D ]\}}t||| qJW |j| jd W dQ R X |dfS )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.
        T)r0   NF)	r{   r
   r   r?   r   r
  r   rL   r   )r(   r  r   rV   createdr   r   r)   r)   r*   update_or_createT  s    zQuerySet.update_or_createc             K   s   |pi }dd |j  D }|j| | jjj}g }xV|D ]N}y| jjj| W q8 tjk
r   ||kott| j|j	s|j
| Y q8X q8W |rtjd| jjjdjt|f |S )z
        Prepare `params` for creating a model instance based on the given
        kwargs; for use by get_or_create().
        c             S   s   i | ]\}}t |kr||qS r)   )r   )r6   r   r   r)   r)   r*   r^   n  s    z2QuerySet._extract_model_params.<locals>.<dictcomp>z)Invalid field name(s) for model %s: '%s'.z', ')rH   r   r1   r9   Z_property_namesr:   r   FieldDoesNotExistr  fsetr  r   r   joinsorted)r(   r  r   r	  Zproperty_namesZinvalid_paramsparamr)   r)   r*   r  h  s"    


zQuerySet._extract_model_paramsc             G   s   |r
|}n(t | jjd}|r2t|ttf r2|f}|dkrBtd| jj sTt	d| j
 }|jjdd |jjdd |jj|  |j S )	zy
        Return the earliest object according to fields (if given) or by the
        model's Meta.get_latest_by.
        Z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.r3   )r   T)force_empty)r  r1   r9   r   rn   r   r   r@   	is_slicedr   r   r   clear_orderingadd_orderingr   )r(   rl   r   rV   r)   r)   r*   	_earliest  s    zQuerySet._earliestc             G   s
   | j | S )N)r  )r(   rl   r)   r)   r*   earliest  s    zQuerySet.earliestc             G   s   | j  j| S )N)reverser  )r(   rl   r)   r)   r*   latest  s    zQuerySet.latestc             C   s,   x&| j r| n| jddd D ]}|S W dS )z@Return the first object of a query or None if no match is found.r   Nr3   )orderedr   )r(   rV   r)   r)   r*   first  s    "zQuerySet.firstc             C   s0   x*| j r| j n| jddd D ]}|S W dS )z?Return the last object of a query or None if no match is found.z-pkNr3   )r  r  r   )r(   rV   r)   r)   r*   last  s    &zQuerySet.lastr   )
field_namec      
         s   | j j std| jj}dd |jD } dkrb|j j rb |krb| j j fkrbt	d  |dk	r|sti S dj
 }t| j jj}t|}|r|t|k rf }xZtdt||D ]0}||||  }	|t| jf ||	ij 7 }qW n| jf ||ij }n| j } fd	d
|D S )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_bulkc             S   s$   g | ]}t |jd kr|jd qS )r3   r   )rc   rl   )r6   
constraintr)   r)   r*   r8     s   z$QuerySet.in_bulk.<locals>.<listcomp>r   z;in_bulk()'s field_name must be a unique field but %r isn't.Nz{}__inr   c                s   i | ]}|t | qS r)   )r  )r6   rV   )r  r)   r*   r^     s    z$QuerySet.in_bulk.<locals>.<dictcomp>)r@   r  r   r1   r9   Ztotal_unique_constraintsr:   uniquer   r   formatr   r?   r   Zmax_query_paramsrn   rc   rb   r   r   r   )
r(   Zid_listr  r   Zunique_fieldsZ
filter_keyr   r   offsetbatchr)   )r  r*   in_bulk  s0    


"zQuerySet.in_bulkc             C   s   | j d | jj std| jjs,| jjr4td| jdk	rFtd| j }d|_	d|j_
d|j_|jjdd t|jd	}|j| |j \}}d| _||fS )
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()TF)r  )r0   )_not_support_combined_queriesr@   r  r   distinctr   r   re   r   r{   r   select_relatedr  r   r?   Zcollectr$  ry   )r(   Z	del_query	collectorZdeletedZ_rows_countr)   r)   r*   r$    s"    


zQuerySet.deletec          	   C   s<   | j j }tj|_|j|jt}|r8| |jS Q R X dS )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   )	r@   r   r   ZDeleteQueryrr   rA   rB   r   Zrowcount)r(   r0   r@   cursorr)   r)   r*   _raw_delete  s    
zQuerySet._raw_deletec          	   K   sv   | j d | jj stdd| _| jjtj}|j| i |_	t
j| jd |j| jjt}W dQ R X d| _|S )z~
        Update all elements in the current QuerySet, setting all the given
        fields to the appropriate values.
        r   z2Cannot update a query once a slice has been taken.T)r0   N)r%  r@   r  r   r{   r   r   UpdateQueryZadd_update_valuesr   r
   Zmark_for_rollback_on_errorr?   rA   rB   r   ry   )r(   r   r@   rowsr)   r)   r*   r     s    

zQuerySet.updatec             C   sH   | j j std| j jtj}|j| i |_d| _|j	| j
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).
        z2Cannot update a query once a slice has been taken.N)r@   r  r   r   r   r+  Zadd_update_fieldsr   ry   rA   r?   rB   r   )r(   r   r@   r)   r)   r*   _update  s    
zQuerySet._updatec             C   s$   | j d kr| jj| jdS t| j S )N)r0   )ry   r@   Zhas_resultsr?   r   )r(   r)   r)   r*   exists&  s    
zQuerySet.existsc             C   s   t | jf| j  d| _d S )NT)prefetch_related_objectsry   r|   r}   )r(   r)   r)   r*   _prefetch_related_objects+  s    z"QuerySet._prefetch_related_objects)r   c            K   s   | j jf | j|d|S )N)r0   r   )r@   explainr?   )r(   r   optionsr)   r)   r*   r1  0  s    zQuerySet.explainc             C   s6   |d kr| j }t|| j|||d}| jd d  |_|S )N)r1   r	  translationsr0   )r?   RawQuerySetr1   r|   )r(   	raw_queryr	  r3  r0   r   r)   r)   r*   raw7  s
    zQuerySet.rawc             O   s.   | j  }|r|jf |}||_|jj| |S )N)r   annotatere   r@   Z
set_values)r(   rl   expressionsr   r)   r)   r*   _values>  s    zQuerySet._valuesc             O   s"   |t |7 }| j||}t|_|S )N)rn   r9  r[   r~   )r(   rl   r8  r   r)   r)   r*   r   F  s    zQuerySet.values)flatnamedc            G   s   |r|rt d|r(t|dkr(t ddd |D }g }i }d}xl|D ]d}t|drt|d|jjj }	x"|	t| }
|d7 }|
|krlP qlW |||
< |j|
 qH|j| qHW | j	||}|rt
n
|rtnt|_|S )Nz*'flat' and 'named' can't be used together.r3   zH'flat' is not valid when values_list is called with more than one field.c             S   s   h | ]}t |d s|qS )resolve_expression)hasattr)r6   r7   r)   r)   r*   	<setcomp>R  s    z'QuerySet.values_list.<locals>.<setcomp>r<  r   )r   rc   r=  r  rr   r,   lowerstrr  r9  rm   rt   rd   r~   )r(   r:  r;  rl   field_namesre   r8  counterr;   Zfield_id_prefixZfield_idr   r)   r)   r*   values_listL  s0    

zQuerySet.values_listASCc             C   sj   |dkst d|dks t d| jt||t d	t|d
jdddj jddj|dkr`dndd S )z
        Return a list of date objects representing all available dates for
        the given field_name, scoped to 'kind'.
        yearmonthweekdayz8'kind' must be one of 'year', 'month', 'week', or 'day'.rD  DESCz''order' must be either 'ASC' or 'DESC'.)r   )	datefieldplain_fieldrJ  T)r:  F)plain_field__isnull- )rE  rF  rG  rH  )rD  rI  )	r   r7  r   r   r   rC  r&  r   r   )r(   r  kindorderr)   r)   r*   datesk  s    

zQuerySet.datesc             C   s   |dkst d|dks t dtjr8|dkr<tj }nd}| jt||t ||dt|dj	dddj
 jddj|d
krdndd S )z
        Return a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        rE  rF  rG  rH  hourminutesecondzT'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'.rD  rI  z''order' must be either 'ASC' or 'DESC'.N)r   tzinfois_dst)datetimefieldrK  rW  T)r:  F)rL  rM  rN  )rE  rF  rG  rH  rR  rS  rT  )rD  rI  )r   r   ZUSE_TZr   Zget_current_timezoner7  r   r   r   rC  r&  r   r   )r(   r  rO  rP  rU  rV  r)   r)   r*   	datetimes{  s$    


zQuerySet.datetimesc             C   s   | j  }|jj  |S )zReturn an empty QuerySet.)r   r@   Z	set_empty)r(   r   r)   r)   r*   none  s    
zQuerySet.nonec             C   s   | j  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.
        )r   )r(   r)   r)   r*   all  s    zQuerySet.allc             O   s   | j d | jd||S )za
        Return a new QuerySet instance with the args ANDed to the existing
        set.
        r   F)r%  _filter_or_exclude)r(   r   r   r)   r)   r*   r     s    
zQuerySet.filterc             O   s   | j d | jd||S )zc
        Return a new QuerySet instance with NOT (args) ANDed to the existing
        set.
        excludeT)r%  r[  )r(   r   r   r)   r)   r*   r\    s    
zQuerySet.excludec             C   sN   |s|r| j j std| j }| jr<d| _|||f|_n|j||| |S )Nz2Cannot filter a query once a slice has been taken.F)r@   r  r   r   r   r   r   )r(   r   r   r   r   r)   r)   r*   r[    s    zQuerySet._filter_or_excludec             C   s0   |r| j jt||  n| j jt|| d S )N)rx   add_qr   )r(   r   r   r   r)   r)   r*   r     s    z#QuerySet._filter_or_exclude_inplacec             C   s6   t |tr"| j }|jj| |S | jdf |dS dS )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.
        F)r   r   N)r   r   r   r@   r]  r[  )r(   Z
filter_objr   r)   r)   r*   complex_filter  s
    

zQuerySet.complex_filter)rZ  c            G   sP   | j  }|jjd |jj  | jftdd |D  |j_||j_||j_|S )NTc             s   s   | ]}|j V  qd S )N)r@   )r6   r   r)   r)   r*   rf     s    z-QuerySet._combinator_query.<locals>.<genexpr>)r   r@   r  Zclear_limitsrn   Zcombined_queriesr   Zcombinator_all)r(   r   rZ  other_qsr   r)   r)   r*   _combinator_query  s    
zQuerySet._combinator_queryc            G   sh   t | trTdd |D }|s | S t|dkr4|d S |d jd|dd  d|iS | jd|d|iS )	Nc             S   s   g | ]}t |ts|qS r)   )r   r   )r6   qr)   r)   r*   r8     s    z"QuerySet.union.<locals>.<listcomp>r3   r   unionrZ  )rb  )rb  )r   r   rc   r`  )r(   rZ  r_  r   r)   r)   r*   rb    s    
 zQuerySet.unionc             G   s8   t | tr| S x|D ]}t |tr|S qW | jd| S )Nintersection)rc  )r   r   r`  )r(   r_  r   r)   r)   r*   rc    s    


zQuerySet.intersectionc             G   s   t | tr| S | jd| S )N
difference)rd  )r   r   r`  )r(   r_  r)   r)   r*   rd    s    
zQuerySet.differencec             C   sJ   |r|rt d| j }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)	r   r   r{   r@   r   Zselect_for_update_nowaitZselect_for_update_skip_lockedZselect_for_update_ofZselect_for_no_key_update)r(   ZnowaitZskip_lockedZofZno_keyrV   r)   r)   r*   r      s    zQuerySet.select_for_updatec             G   sT   | j d | jdk	rtd| j }|dkr6d|j_n|rH|jj| nd|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.
        r'  Nz>Cannot call select_related() after .values() or .values_list()FT)N)r%  re   r   r   r@   r'  Zadd_select_related)r(   rl   rV   r)   r)   r*   r'    s    	


zQuerySet.select_relatedc             G   st   | j d | j }|dkr"f |_nNx@|D ]8}t|tr<|j}|jtdd }|| jj	kr(t
dq(W |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_relatedNr3   r   z:prefetch_related() is not supported with FilteredRelation.)N)r%  r   r|   r   Prefetchprefetch_tosplitr   r@   _filtered_relationsr   )r(   lookupsr   lookupr)   r)   r*   re  &  s    	


zQuerySet.prefetch_relatedc             O   s   | j d | j||ddS )z
        Return a query set in which the returned objects have been annotated
        with extra data or aggregations.
        r7  T)rC   )r%  	_annotate)r(   r   r   r)   r)   r*   r7  =  s    
zQuerySet.annotatec             O   s   | j d | j||ddS )zW
        Return a query set with added aliases for extra data or aggregations.
        r   F)rC   )r%  rl  )r(   r   r   r)   r)   r*   r   E  s    
zQuerySet.aliasc       
      C   s\  | j |t|j  dd i }xP|D ]H}y|j|krBtd|j W n tk
r`   tdY nX |||j< q$W |j| | j }| j}|d krt	t
jdd | jjj D }xV|j D ]J\}}	||krtd| t|	tr|jj|	| q|jj|	|d|d	 qW xN|jjj D ]>\}}	||kr|	jr|jd krFd
|j_n
|jj  P qW |S )Nr7  )r   zQThe named annotation '%s' conflicts with the default name for another annotation.z$Complex annotations require an aliasc             s   s,   | ]$}t |d r|j|jfn|jfV  qdS )r5   N)r=  rO   r5   )r6   r;   r)   r)   r*   rf   _  s   z%QuerySet._annotate.<locals>.<genexpr>z8The annotation '%s' conflicts with a field on the model.F)r   rC   T)r   rn   r   r   r   r   r   r   re   setr   from_iterabler1   r9   Z
get_fieldsrH   r   r   r@   Zadd_filtered_relationr   r   r   group_byZset_group_by)
r(   r   r   rC   r   r   r   r]   r   r   r)   r)   r*   rl  L  s@    





zQuerySet._annotatec             G   s8   | j j std| j }|j jdd |j j|  |S )z9Return a new QuerySet instance with the ordering changed.z3Cannot reorder a query once a slice has been taken.F)r  )r@   r  r   r   r  r  )r(   rA  rV   r)   r)   r*   r   w  s    zQuerySet.order_byc             G   s4   | j d | jj std| j }|jj|  |S )zX
        Return a new QuerySet instance that will select only distinct results.
        r&  z:Cannot create distinct fields once a slice has been taken.)r%  r@   r  r   r   Zadd_distinct_fields)r(   rA  rV   r)   r)   r*   r&    s    
zQuerySet.distinctc             C   s>   | j d | jj std| j }|jj|||||| |S )z%Add extra SQL fragments to the query.extraz1Cannot change a query once a slice has been taken)r%  r@   r  r   r   Z	add_extra)r(   rC   wherer	  Ztablesr   Zselect_paramsr   r)   r)   r*   rp    s    
zQuerySet.extrac             C   s*   | j jrtd| j }|j j |j _|S )z%Reverse the ordering of the QuerySet.z3Cannot reverse a query once a slice has been taken.)r@   r  r   r   Zstandard_ordering)r(   r   r)   r)   r*   r    s
    zQuerySet.reversec             G   sH   | j d | jdk	rtd| j }|dkr8|jj  n|j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())N)r%  re   r   r   r@   Zclear_deferred_loadingZadd_deferred_loading)r(   rl   r   r)   r)   r*   rr    s    

zQuerySet.deferc             G   sv   | j d | jdk	rtd|dkr,tdx0|D ](}|jtdd }|| jjkr2tdq2W | j }|j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()z*Cannot pass None as an argument to only().r3   r   z.only() is not supported with FilteredRelation.)N)
r%  re   r   rh  r   r@   ri  r   r   Zadd_immediate_loading)r(   rl   r;   r   r)   r)   r*   rs    s    


zQuerySet.onlyc             C   s   | j  }||_|S )z;Select which database this QuerySet should execute against.)r   rv   )r(   r   r   r)   r)   r*   r0     s    zQuerySet.usingc             C   sL   t | trdS | jjs| jjr"dS | jjrD| jj jrD| jj rDdS dS dS )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).
        TFN)	r   r   r@   Zextra_order_byr   Zdefault_orderingZget_metaZorderingro  )r(   r)   r)   r*   r    s    

zQuerySet.orderedc             C   s6   | j r| jptj| jf| jS | jp4tj| jf| jS )z7Return the database used if this query is executed now.)r{   rv   r	   Zdb_for_writer1   rw   db_for_read)r(   r)   r)   r*   r?     s    zQuerySet.dbc             C   sF   d| _ |dkr| j}tj| j|d}|j|||d |j|dj|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.
        TN)r   )r6  )r0   )r{   r?   r   ZInsertQueryr1   Zinsert_valuesrA   rB   )r(   r   rl   returning_fieldsr6  r0   r   r@   r)   r)   r*   _insert  s    zQuerySet._insertc       
   	      s   |rt | j jj rtdt | j j}t|j|d} rHt |n| g }t | j jj	}xj fddt
dt D D ]F}	|r| r|j| j|	|| j| jjj|d q| j|	|| j|d qW |S )zU
        Helper method for bulk_create() to insert objs one batch at a time.
        z:This database backend does not support ignoring conflicts.r3   c                s   g | ]}||   qS r)   r)   )r6   r\   )r   r   r)   r*   r8     s    z,QuerySet._batched_insert.<locals>.<listcomp>r   )rl   r0   ru  r   )rl   r0   r   )r   r?   r   Zsupports_ignore_conflictsr   r   maxr   r   r   rb   rc   extendrv  r1   r9   r   )
r(   r   rl   r   r   r   r  Zinserted_rowsZbulk_returnitemr)   )r   r   r*   r     s    &
zQuerySet._batched_insertc             K   s,   | j  }|jrd|j_d|_|jj| |S )zc
        Return a copy of the current QuerySet that's ready for another
        operation.
        TF)_clonerz   r@   Zfilter_is_stickyr   r   )r(   r   rV   r)   r)   r*   r     s    zQuerySet._chainc             C   sZ   | j | j| jj | j| jd}| j|_| j|_| jdd |_| j	|_	| j
|_
| j|_|S )zi
        Return a copy of the current QuerySet. A lightweight alternative
        to deepcopy().
        )r1   r@   r0   r   N)rr   r1   r@   r   rv   rw   rz   r{   r|   rG   r~   re   )r(   cr)   r)   r*   rz    s    zQuerySet._clonec             C   s4   | j d krt| j| | _ | jr0| j r0| j  d S )N)ry   r   r~   r|   r}   r0  )r(   r)   r)   r*   r   *  s    
zQuerySet._fetch_allc             C   s
   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)rz   )r(   r)   r)   r*   _next_is_sticky0  s    zQuerySet._next_is_stickyc             C   sf   | j dk	rbt| jjt|jjksRt| jjt|jjksRt| jjt|jjkrbtd| jj dS )z.Check that two QuerySet classes may be merged.Nz?Merging '%s' classes must involve the same values in each case.)	re   rm  r@   r`   r_   ra   r   rr   r,   )r(   r   r)   r)   r*   r   >  s    
zQuerySet._merge_sanity_checkc             C   s0   x*|j j D ]\}}| j j|i j| qW dS )zX
        Keep track of all known related objects from either QuerySet instance.
        N)rG   rH   
setdefaultr   )r(   r   r;   Zobjectsr)   r)   r*   r   I  s    z%QuerySet._merge_known_related_objectsc             O   s6   | j rt| j dkrtd| jj||}| j|_|S )Nr3   z0Cannot use multi-field values as a filter value.)re   rc   r   r@   r<  rv   )r(   r   r   r@   r)   r)   r*   r<  P  s
    zQuerySet.resolve_expressionc             K   s   | j j| dS )z}
        Update hinting information for use by routers. Add new key/values or
        overwrite existing key/values.
        N)rw   r   )r(   r   r)   r)   r*   
_add_hintsZ  s    zQuerySet._add_hintsc             C   s
   | j j S )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.
        )r@   Zhas_filters)r(   r)   r)   r*   _has_filtersa  s    zQuerySet._has_filtersc             C   s0   t dd | D }|r,td|dj|f d S )Nc             s   s    | ]}t |d st|V  qdS )r<  N)r=  r@  )r6   r   r)   r)   r*   rf   k  s    z<QuerySet._validate_values_are_expressions.<locals>.<genexpr>z-QuerySet.%s() received non-expression(s): %s.z, )r  r   r  )r   r   Zinvalid_argsr)   r)   r*   r   i  s    z)QuerySet._validate_values_are_expressionsc             C   s    | j jrtd|| j jf d S )Nz2Calling QuerySet.%s() after %s() is not supported.)r@   r   r   )r(   r   r)   r)   r*   r%  t  s    z&QuerySet._not_support_combined_queries)NNNN)r   )NF)N)N)N)N)rD  )rD  NN)T)NNNNNN)NFNF)F)^r,   r-   r.   rZ   r+   propertyr@   setterr   Zqueryset_onlyclassmethodr   r   r   r   r   rY   r   r   r   r   r   r   r   r   r   r   r   r   r   r  Zalters_datar
  r  r  r  r  r  r  r  r#  r$  r*  r   r-  r.  r0  r1  r6  r9  r   rC  rQ  rX  rY  rZ  r   r\  r[  r   r^  r`  rb  rc  rd  r   r'  re  r7  r   rl  r   r&  rp  r  rr  rs  r0   r  r?   rv  r   r   rz  r   r|  r   r   r<  r~  r  staticmethodr   r%  r)   r)   r)   r*   ru      s   

!

$ 

@
*

'


	
+	 
	


ru   c               @   s   e Zd Zdd ZdS )InstanceCheckMetac             C   s   t |to|jj S )N)r   ru   r@   Zis_empty)r(   instancer)   r)   r*   __instancecheck__}  s    z#InstanceCheckMeta.__instancecheck__N)r,   r-   r.   r  r)   r)   r)   r*   r  |  s   r  c               @   s   e Zd ZdZdd ZdS )r   zz
    Marker class to checking if a queryset is empty by .none():
        isinstance(qs.none(), EmptyQuerySet) -> True
    c             O   s   t dd S )Nz#EmptyQuerySet can't be instantiated)r   )r(   r   r   r)   r)   r*   r+     s    zEmptyQuerySet.__init__N)r,   r-   r.   rZ   r+   r)   r)   r)   r*   r     s   r   )	metaclassc               @   s   e Zd ZdZddf dddfddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zedd Zdd Zedd  Zed!d" ZdS )#r4  zo
    Provide an iterator which converts the results of raw SQL queries into
    annotated model instances.
    Nc             C   sZ   || _ || _|| _|pi | _|p0tj|| j|d| _|| _|p@i | _	d | _
f | _d| _d S )N)r   r0   r	  F)r5  r1   rv   rw   r   ZRawQueryr?   r@   r	  r3  ry   r|   r}   )r(   r5  r1   r@   r	  r3  r0   r   r)   r)   r*   r+     s    

zRawQuerySet.__init__c                sl   t j jj  fddjjjD }fddtjD } fdd|D }dd |D }|||fS )z1Resolve the init field names and value positions.c                s    g | ]} |j jkr|qS r)   )columncolumns)r6   r7   )	converterr(   r)   r*   r8     s    z8RawQuerySet.resolve_model_init_order.<locals>.<listcomp>c                s"   g | ]\}}| j kr||fqS r)   )model_fields)r6   posr  )r(   r)   r*   r8     s    c                s   g | ]}j j |jqS r)   )r  indexr  )r6   r7   )r  r(   r)   r*   r8     s    c             S   s   g | ]
}|j qS r)   )r5   )r6   r7   r)   r)   r*   r8     s    )	r   r?   introspectionidentifier_converterr1   r9   rl   ri   r  )r(   Zmodel_init_fieldsannotation_fieldsZmodel_init_ordermodel_init_namesr)   )r  r(   r*   resolve_model_init_order  s    z$RawQuerySet.resolve_model_init_orderc             G   s(   | j  }|dkrf |_n|j| |_|S )z#Same as QuerySet.prefetch_related()N)N)rz  r|   )r(   rj  r   r)   r)   r*   re    s
    zRawQuerySet.prefetch_relatedc             C   s   t | jf| j  d| _d S )NT)r/  ry   r|   r}   )r(   r)   r)   r*   r0    s    z%RawQuerySet._prefetch_related_objectsc          	   C   s:   | j | j| j| j| j| j| j| jd}| jdd |_|S )zSame as QuerySet._clone())r1   r@   r	  r3  r0   r   N)	rr   r5  r1   r@   r	  r3  rv   rw   r|   )r(   r{  r)   r)   r*   rz    s
    zRawQuerySet._clonec             C   s2   | j d krt| j | _ | jr.| j r.| j  d S )N)ry   r   r   r|   r}   r0  )r(   r)   r)   r*   r     s    
zRawQuerySet._fetch_allc             C   s   | j   t| jS )N)r   rc   ry   )r(   r)   r)   r*   r     s    zRawQuerySet.__len__c             C   s   | j   t| jS )N)r   r   ry   )r(   r)   r)   r*   r     s    zRawQuerySet.__bool__c             C   s   | j   t| jS )N)r   r   ry   )r(   r)   r)   r*   rY     s    zRawQuerySet.__iter__c             #   s   j }t| jjd jt| |}t j}zĈ j \}}} jjj	j
|krXtjd j} fdd jD }|jdd |D }	|	r|j||	}xX|D ]Pfdd|D }
|j|||
}|rx |D ]\}}t|||  qW |V  qW W d t jdr jjr jjj  X d S )NZSQLCompilerz&Raw query must include the primary keyc                s   g | ]} j j|qS r)   )r  r   )r6   r{  )r(   r)   r*   r8     s    z(RawQuerySet.iterator.<locals>.<listcomp>c             S   s$   g | ]}|r|j |jjjnd qS )N)Zget_colr1   r9   Zdb_table)r6   r7   r)   r)   r*   r8     s    c                s   g | ]} | qS r)   r)   )r6   r  )r   r)   r*   r8     s    r)  )r?   r   r   rP   r@   r   r  r1   r9   r   r5   r   r  r  Zget_convertersZapply_convertersrJ   rL   r=  r)  close)r(   r?   rP   r@   r  Zmodel_init_posr  rR   rl   
convertersZmodel_init_valuesr  r  r  r)   )r(   r   r*   r     s0    

zRawQuerySet.iteratorc             C   s   d| j j| jf S )Nz<%s: %s>)rr   r,   r@   )r(   r)   r)   r*   r     s    zRawQuerySet.__repr__c             C   s   t | | S )N)r   )r(   r   r)   r)   r*   r     s    zRawQuerySet.__getitem__c             C   s   | j ptj| jf| jS )z7Return the database used if this query is executed now.)rv   r	   rt  r1   rw   )r(   r)   r)   r*   r?     s    zRawQuerySet.dbc             C   s&   t | j| j| jj|d| j| j|dS )z<Select the database this RawQuerySet should execute against.)r0   )r1   r@   r	  r3  r0   )r4  r5  r1   r@   r   r	  r3  )r(   r   r)   r)   r*   r0     s
    zRawQuerySet.usingc             C   sR   | j j }xB| jj D ]4\}}y|j|}W n tk
r@   Y qX |||< qW |S )zg
        A list of model field names in the order they'll appear in the
        query results.
        )r@   Zget_columnsr3  rH   r  r   )r(   r  Z
query_nameZ
model_namer  r)   r)   r*   r    s    
zRawQuerySet.columnsc             C   sB   t | j jj}i }x*| jjjD ]}|j \}}||||< qW |S )z1A dict mapping column names to model field names.)r   r?   r  r  r1   r9   rl   Zget_attname_column)r(   r  r  r;   rO   r  r)   r)   r*   r    s    zRawQuerySet.model_fields)r,   r-   r.   rZ   r+   r  re  r0  rz  r   r   r   rY   r   r   r   r  r?   r0   r    r  r  r)   r)   r)   r*   r4    s$   
		#	r4  c               @   sN   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dS )rf  Nc             C   sr   || _ || _|d k	r>t|ts6t|dr>t|jt r>td|rbt	j
|jt	d d |g | _|| _|| _d S )Nr~   zAPrefetch querysets cannot use raw(), values(), and values_list().r3   r>   )prefetch_throughrg  r   r4  r=  
issubclassr~   r/   r   r   r  rh  r%   to_attr)r(   rk  r%   r  r)   r)   r*   r+   $  s    

 zPrefetch.__init__c             C   s,   | j j }| jd k	r(| jjg dd|d< |S )NT)ry   r}   r%   )r   r   r%   r   )r(   Zobj_dictr)   r)   r*   r   9  s    

zPrefetch.__getstate__c             C   s$   |t  | j | _|t  | j | _d S )N)r   r  rg  )r(   prefixr)   r)   r*   
add_prefixC  s    zPrefetch.add_prefixc             C   s   t j| jjt d |d  S )Nr3   )r   r  rg  rh  )r(   levelr)   r)   r*   get_current_prefetch_toG  s    z Prefetch.get_current_prefetch_toc             C   s2   | j jt}|| }| jo(|t|d k}||fS )Nr3   )rg  rh  r   r  rc   )r(   r  partsr  as_attrr)   r)   r*   get_current_to_attrJ  s    zPrefetch.get_current_to_attrc             C   s   | j || jkr| jS d S )N)r  rg  r%   )r(   r  r)   r)   r*   get_current_querysetP  s    zPrefetch.get_current_querysetc             C   s   t |tstS | j|jkS )N)r   rf  NotImplementedrg  )r(   r   r)   r)   r*   __eq__U  s    
zPrefetch.__eq__c             C   s   t | j| jfS )N)hashrr   rg  )r(   r)   r)   r*   __hash__Z  s    zPrefetch.__hash__)NN)r,   r-   r.   r+   r   r  r  r  r  r  r  r)   r)   r)   r*   rf  #  s   

rf  c             C   s@   g }x6| D ].}t |ts t|}|r.|j| |j| q
W |S )z(Normalize lookups into Prefetch objects.)r   rf  r  r  )rj  r  retrk  r)   r)   r*   normalize_prefetch_lookups^  s    


r  c                s  | sdS i }t  }t  }tt|}xd|r|j }|j|krZ|jdk	r(td|j q(| }|jjt	}xt
|D ]\}	}
|sP |j|	}||kr|| }qvd}x@|D ]8}t|dsy
i |_W q ttfk
r   d}P Y qX qW |sP |d }|j|	d }t||
|\}}} |s6td|
|jj|jf |	t|d kr`|dkr`td	|j d}|dk	r fd
d|D }|rt||||	\}}||ko||ko||ks|||< tt||}|j| |j| |j| qvg }x|D ]}|
t|df krt|jj|
}n,yt||
}W n tjk
rH   wY nX |dkrXqt|trp|j| n
|j| qW |}qvW q(W dS )z|
    Populate prefetched object caches for a list of model instances based on
    the lookups/Prefetch instances given.
    Nzl'%s' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups.T_prefetched_objects_cacheFr   zQCannot find '%s' on %s object, '%s' is an invalid parameter to prefetch_related()r3   zp'%s' does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().c                s   g | ]} |s|qS r)   r)   )r6   rV   )
is_fetchedr)   r*   r8     s    z,prefetch_related_objects.<locals>.<listcomp>) rm  r  reversedpoprg  r%   r   r  rh  r   ri   r  r=  r  r   r   r  get_prefetcherrr   r,   rc   prefetch_one_levelr   rx  addr  r   r   r   ZObjectDoesNotExistr   r  )Zmodel_instancesZrelated_lookupsZdone_queriesZauto_lookupsZfollowed_descriptorsZall_lookupsrk  Zobj_listZthrough_attrsr  through_attrrg  Zgood_objectsrV   Z	first_objr  
prefetcherZ
descriptor
attr_foundZobj_to_fetchadditional_lookupsZnew_lookupsZnew_obj_listZnew_objr)   )r  r*   r/  j  s    












	


r/  c                s   fdd}d}|}t | j d}|dkr6t|  }ntd}|rt|drT|}|j}nVt |  }t|drl|} krtt | jdtrfdd}	|	}n fdd	}
|
}||||fS )
a  
    For the attribute 'through_attr' on the given instance, find
    an object that has a get_prefetch_queryset().
    Return a 4 tuple containing:
    (the object with get_prefetch_queryset (or None),
     the descriptor object representing this relationship (or None),
     a boolean that is False if the attribute was not found at all,
     a function that takes an instance and returns a boolean that is True if
     the attribute has already been fetched for that instance)
    c                s
   t |  S )N)r=  )r  )r  r)   r*   has_to_attr_attribute  s    z-get_prefetcher.<locals>.has_to_attr_attributeNTget_prefetch_querysetc                s
    | j kS )N)r   )r  )r  r)   r*   has_cached_property  s    z+get_prefetcher.<locals>.has_cached_propertyc                s
    | j kS )N)r  )r  )r  r)   r*   in_prefetched_cache   s    z+get_prefetcher.<locals>.in_prefetched_cache)r  rr   r=  rM   r   r    )r  r  r  r  r  r  Zrel_obj_descriptorr  rX   r  r  r)   )r  r  r*   r    s*    


r  c             C   s  |j | |j|\}}}}}}	dd t|df D }
|
r>f |_t|}i }x&|D ]}||}|j|g j| qPW |j|\}}|r| r| d j}y|j	j
| W n tjk
r   Y nX d}t|j||jt|jjtd |k}x| D ]}||}|j|g }|rT|r|d nd}|r2t||| n |	rFt||| n||jj|< q|rht||| qt||}|r|jdk	r|j|j}n|j }||_d|_||j|< qW ||
fS )	aL  
    Helper function for prefetch_related_objects().

    Run prefetches on all instances using the prefetcher object,
    assigning results to relevant caches in instance.

    Return the prefetched objects along with any additional prefetches that
    must be done due to prefetch_related lookups found from default managers.
    c             S   s   g | ]}t j |qS r)   )r   )r6   Zadditional_lookupr)   r)   r*   r8   G  s    z&prefetch_one_level.<locals>.<listcomp>r|   r   z2to_attr={} conflicts with a field on the {} model.r3   NT)r  r  r  r|   r   r}  r  r  rr   r9   r:   r   r  r   r   r,   rc   r  rh  r   r   rL   r   Zfields_cacher%   Z_apply_rel_filtersZget_querysetry   r}   r  )Z	instancesr  rk  r  Zrel_qsZrel_obj_attrZinstance_attrZsingleZ
cache_nameZis_descriptorr  Zall_related_objectsZrel_obj_cacherX   Zrel_attr_valr  r  r1   msgZleafrV   Zinstance_attr_valvalsvalr   r   r)   r)   r*   r  '  sP    



r  c               @   s    e Zd ZdZdd Zdd ZdS )RelatedPopulatora  
    RelatedPopulator is used for select_related() object instantiation.

    The idea is that each select_related() model will be populated by a
    different RelatedPopulator instance. The RelatedPopulator instances get
    klass_info and select (computed in SQLCompiler) plus the used db as
    input for initialization. That data is used to compute which columns
    to use, how to instantiate the model, and how to populate the links
    between the objects.

    The actual creation of the objects is done in populate() method. This
    method gets row and from_obj as input and populates the select_related()
    model instance.
    c                s   || _ |d }|d }|sV|d | _|d d | _dd | j| j D | _d | _nXfdd|D  d	d
 |d jjD } fdd|D | _tj fdd| jD  | _|d | _	| jj
| j	jjj| _t|| j | _|d | _|d | _d S )Nr2   from_parentr   r3   c             S   s   g | ]}|d  j jqS )r   )r4   r5   )r6   r7   r)   r)   r*   r8     s    z-RelatedPopulator.__init__.<locals>.<listcomp>c                s   i | ]}| | d  j jqS )r   )r4   r5   )r6   rg   )rC   r)   r*   r^     s    z-RelatedPopulator.__init__.<locals>.<dictcomp>c             s   s   | ]}|j V  qd S )N)r5   )r6   r7   r)   r)   r*   rf     s    z,RelatedPopulator.__init__.<locals>.<genexpr>r1   c                s   g | ]}| kr|qS r)   r)   )r6   r5   )attname_indexesr)   r*   r8     s    c                s   g | ]} | qS r)   r)   )r6   r5   )r  r)   r*   r8     s    local_setterremote_setterr>   )r?   
cols_startcols_endrS   reorder_for_initr9   r   r<   rj   rR   r  r   r5   pk_idxrF   rT   r  r  )r(   rD   rC   r?   r2   r  Zmodel_init_attnamesr)   )r  rC   r*   r+     s"    


zRelatedPopulator.__init__c             C   s   | j r| j |}n|| j| j }|| j d kr6d }n0| jj| j| j|}x| jD ]}|j	|| qRW | j
|| |d k	r| j|| d S )N)r  r  r  r  rR   rJ   r?   rS   rT   rK   r  r  )r(   rU   Zfrom_objZobj_datarV   Zrel_iterr)   r)   r*   rK     s    zRelatedPopulator.populateN)r,   r-   r.   rZ   r+   rK   r)   r)   r)   r*   r    s   .r  c             C   s8   g }| j dg }x"|D ]}t|||}|j| qW |S )Nrelated_klass_infos)r   r  r  )rD   rC   r?   	iteratorsr  Zrel_klass_infoZrel_clsr)   r)   r*   rF     s    
rF   )N)GrZ   r   r<   r   	itertoolsr   r   Zdjango.confr   Zdjango.corer   Z	django.dbr   r   r   r   r	   r
   Zdjango.db.modelsr   r   r   r   Zdjango.db.models.constantsr   Zdjango.db.models.deletionr   Zdjango.db.models.expressionsr   r   r   r   r   r   Zdjango.db.models.functionsr   r   Zdjango.db.models.query_utilsr   r   Zdjango.db.models.sql.constantsr   r   Zdjango.db.models.utilsr   r   Zdjango.utilsr   Zdjango.utils.functionalr    r!   r   r   r$   r/   r[   rd   rm   rt   ru   r   r  r   r4  rf  r  r/  r  r  r  rF   r)   r)   r)   r*   <module>   s`     2         V
 ;
 6dM