
 X                @   s  d  Z  d d l Z d d l Z d d l Z d d l 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 d d l m Z m Z m Z d d l m Z d d	 l m Z d d
 l m Z d d l m Z d d l m Z d d l m  Z  m! Z! m" Z" d d l# m$ Z$ d d l% m& Z& m' Z' d d l( m) Z) d d l* m+ Z+ m, Z, d d l- m. Z. d Z/ e j0 Z0 Gd d   d e1  Z2 Gd d   d e2  Z3 Gd d   d e2  Z4 Gd d   d e2  Z5 Gd d   d e2  Z6 Gd d   d e1  Z7 Gd  d!   d! e8  Z9 Gd" d#   d# e& j: e9   Z; Gd$ d%   d% e1  Z< Gd& d'   d' e1  Z= d d( d)  Z> d* d+   Z? d, d-   Z@ d. d/   ZA Gd0 d1   d1 e1  ZB d2 d3   ZC d S)4zM
The main QuerySet implementation. This provides the public API for the ORM.
    N)OrderedDictdeque)settings)
exceptions)DJANGO_VERSION_PICKLE_KEYIntegrityErrorconnectionsroutertransaction)	DateFieldDateTimeFieldsql)
LOOKUP_SEP)	Collector)F)	AutoField)Trunc)InvalidQueryQcheck_rel_lookup_compatibility)CURSOR)sixtimezone)RemovedInDjango20Warning)cached_property	partition)get_version   c               @   s   e  Z d  Z d d   Z d S)BaseIterablec             C   s   | |  _  d  S)N)queryset)selfr    r!   D/home/ubuntu/projects/ifolica/build/django/django/db/models/query.py__init__'   s    zBaseIterable.__init__N)__name__
__module____qualname__r#   r!   r!   r!   r"   r   &   s   r   c               @   s"   e  Z d  Z d Z d d   Z d S)ModelIterablez=
    Iterable that yields a model instance for each row.
    c             c   s  |  j  } | j } | j j d |  } | j   } | j | j | j } } } | d  k r` d  S| d } | d }	 |	 d |	 d d }
 } d d   | |
 |  D } t | | |  } x1| j	 |  D] } | j
 | | | |
 |   } | rx! | D] } | j | |  q Wn  | rUx1 | j   D]  \ } } t | | | |  q.Wn  | j rx | j j   D]r \ } } t | | j    rqnn  t | | j    } y | | } Wn t k
 rYqnXt | | j |  qnWn  | Vq Wd  S)	Nusingmodelselect_fieldsr      c             S   s    g  |  ] } | d  j  j  q S)r   )targetattname).0fr!   r!   r"   
<listcomp>>   s   	z*ModelIterable.__iter__.<locals>.<listcomp>)r   dbqueryget_compilerexecute_sqlselect
klass_infoannotation_col_mapget_related_populatorsresults_iterfrom_dbpopulateitemssetattr_known_related_objectshasattrget_cache_namegetattrZget_attnameKeyErrorname)r    r   r2   compilerresultsr6   r7   r8   	model_clsr*   Zmodel_fields_startZmodel_fields_end	init_listrelated_populatorsrowobjZrel_populator	attr_nameZcol_posfieldZrel_objspkrel_objr!   r!   r"   __iter__0   sB    		

		zModelIterable.__iter__N)r$   r%   r&   __doc__rP   r!   r!   r!   r"   r'   +   s   r'   c               @   s"   e  Z d  Z d Z d d   Z d S)ValuesIterablezU
    Iterable returned by QuerySet.values() that yields a dict
    for each row.
    c       	      c   s   |  j  } | j } | j | j  } t | j  } t | j  } t | j  } | | | } x( | j   D] } t	 t
 | |   Vql Wd  S)N)r   r3   r4   r2   listvalues_selectextra_selectannotation_selectr:   dictzip)	r    r   r3   rE   field_namesextra_namesannotation_namesnamesrJ   r!   r!   r"   rP   a   s    		zValuesIterable.__iter__N)r$   r%   r&   rQ   rP   r!   r!   r!   r"   rR   [   s   rR   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 r] x | j   D] } t |  VqE Wn t | j	  } t | j  } t | j  } | | | }  j
 r t  j
   f d d   | D } n | } xG | j   D]9 } t t | |     t   f d d   | D  Vq Wd  S)Nc                s%   g  |  ] } |   j  k r |  q Sr!   )_fields)r.   r/   )r   r!   r"   r0      s   	 z/ValuesListIterable.__iter__.<locals>.<listcomp>c             3   s   |  ] }   | Vq d  S)Nr!   )r.   r/   )datar!   r"   	<genexpr>   s    z.ValuesListIterable.__iter__.<locals>.<genexpr>)r   r3   r4   r2   rU   rV   r:   tuplerS   rT   r^   rW   rX   )	r    r3   rE   rJ   rY   rZ   r[   r\   fieldsr!   )r_   r   r"   rP   w   s     			)zValuesListIterable.__iter__N)r$   r%   r&   rQ   rP   r!   r!   r!   r"   r]   q   s   r]   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   sB   |  j  } | j j | j  } x | j   D] } | d Vq+ Wd  S)Nr   )r   r3   r4   r2   r:   )r    r   rE   rJ   r!   r!   r"   rP      s    	zFlatValuesListIterable.__iter__N)r$   r%   r&   rQ   rP   r!   r!   r!   r"   rc      s   rc   c               @   sT  e  Z d  Z d Z d d d d 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 d  d!   Z d" d#   Z d$ d%   Z d& d'   Z d( d)   Z d d* d+  Z d d, d-  Z d d. d/  Z d0 d1   Z d2 d3   Z d d4 d5 d6  Z d d7 d8  Z d d9 d:  Z  d; d<   Z! d= d>   Z" d d? d@  Z# dA dB   Z$ d e$ _% d e$ _ dC dD   Z& d e& _% dE dF   Z' d e' _% dG dH   Z( d e( _% dI e( _ dJ dK   Z) dL dM   Z* d d d dN dO  Z+ dP dQ   Z, dR dS   Z- dT dU   Z. dV dW dX  Z/ dV d dY dZ  Z0 d[ d\   Z1 d] d^   Z2 d_ d`   Z3 da db   Z4 dc dd   Z5 de df   Z6 dI dg dh  Z7 di dj   Z8 dk dl   Z9 dm dn   Z: do dp   Z; dq dr   Z< d d d d d d ds dt  Z= du dv   Z> dw dx   Z? dy dz   Z@ d{ d|   ZA d} d~   ZB eC eB  ZB eC d d    ZD dI dI d d d  ZE d eE _% dI eE _ d d   ZF d d   ZG d d   ZH d d   ZI d d   ZJ d d   ZK d d   ZL d d   ZM d ZN d d   ZO d d   ZP d d   ZQ d eQ _ d S)QuerySetzA
    Represents a lazy database lookup for a set of objects.
    Nc             C   s   | |  _  | |  _ | p i  |  _ | p6 t j |  j   |  _ d  |  _ d |  _ d |  _ g  |  _	 d |  _
 i  |  _ t |  _ d  |  _ d  S)NF)r)   _db_hintsr   ZQueryr3   _result_cache_sticky_filter
_for_write_prefetch_related_lookups_prefetch_doner?   r'   _iterable_classr^   )r    r)   r3   r(   hintsr!   r!   r"   r#      s    									zQuerySet.__init__c             C   s/   d d l  m } | j |     } d | _ | S)Nr   )ManagerT)Zdjango.db.models.managerrn   Zfrom_querysetZ_built_with_as_manager)clsrn   managerr!   r!   r"   
as_manager   s    	zQuerySet.as_managerTc             C   se   |  j    } xR |  j j   D]A \ } } | d k rD d | j | <q t j | |  | j | <q W| S)zD
        Deep copy of a QuerySet doesn't populate the cache
        rg   N)	__class____dict__r=   copydeepcopy)r    memorK   kvr!   r!   r"   __deepcopy__   s    zQuerySet.__deepcopy__c             C   s*   |  j    |  j j   } t   | t <| S)z4
        Allows the QuerySet to be pickled.
        )
_fetch_allrs   rt   r   r   )r    Zobj_dictr!   r!   r"   __getstate__   s    
zQuerySet.__getstate__c             C   s   d  } | j  t  } | rF t   } | | k rL d | | f } qL n d } | rk t j | t d d n  |  j j |  d  S)NzTPickled queryset instance's Django version %s does not match the current version %s.z<Pickled queryset instance's Django version is not specified.
stacklevel   )getr   r   warningswarnRuntimeWarningrs   update)r    statemsgZpickled_versioncurrent_versionr!   r!   r"   __setstate__   s    	zQuerySet.__setstate__c             C   sA   t  |  d  t d   } t |  t k r9 d | d <n  d | S)Nr+   z$...(remaining elements truncated)...z<QuerySet %r>r1   )rS   REPR_OUTPUT_SIZElen)r    r_   r!   r!   r"   __repr__   s    zQuerySet.__repr__c             C   s   |  j    t |  j  S)N)rz   r   rg   )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.
        )rz   iterrg   )r    r!   r!   r"   rP      s    
zQuerySet.__iter__c             C   s   |  j    t |  j  S)N)rz   boolrg   )r    r!   r!   r"   __bool__  s    
zQuerySet.__bool__c             C   s   t  |   j |   S)N)typer   )r    r!   r!   r"   __nonzero__  s    zQuerySet.__nonzero__c             C   s  t  | t f t j  s" t  n  t  | t  r> | d k s t  | t  r | j d k sk | j d k r | j d k s | j d k s t d   |  j d k	 r |  j | St  | t  rR|  j	   } | j d k	 r t
 | j  } n d } | j d k	 rt
 | j  } n d } | j j | |  | j rNt |  d d | j  S| S|  j	   } | j j | | d  t |  d S)zE
        Retrieves an item or slice from the set of results.
        r   Nz#Negative indexing is not supported.r+   )
isinstanceslicer   integer_types	TypeErrorstartstopAssertionErrorrg   _cloneintr3   
set_limitssteprS   )r    rw   qsr   r   r!   r!   r"   __getitem__
  s*    	-!	'zQuerySet.__getitem__c             C   si   |  j  |  t | t  r  | St |  t  r3 |  S|  j   } | j |  | j j | j t j  | S)N)	_merge_sanity_checkr   EmptyQuerySetr   _merge_known_related_objectsr3   combiner   ZAND)r    othercombinedr!   r!   r"   __and__)  s    zQuerySet.__and__c             C   si   |  j  |  t |  t  r  | St | t  r3 |  S|  j   } | j |  | j j | j t j  | S)N)	r   r   r   r   r   r3   r   r   ZOR)r    r   r   r!   r!   r"   __or__4  s    zQuerySet.__or__c             C   s   t  |  j |    S)zc
        An iterator over the results from applying this QuerySet to the
        database.
        )r   rl   )r    r!   r!   r"   iteratorC  s    zQuerySet.iteratorc             O   s   |  j  j r t d   n  xM | D]E } y | j Wn$ t t f k
 rY t d   Yn X| | | j <q" W|  j  j   } xS | j   D]E \ } } | j | | d d | j	 | j
 s t d |   q q W| j |  j | j    S)z
        Returns 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.z#Complex aggregates require an alias
is_summaryTz!%s is not an aggregate expression)r3   distinct_fieldsNotImplementedErrordefault_aliasAttributeErrorr   cloner=   add_annotationannotationscontains_aggregateZget_aggregationr2   keys)r    argskwargsargr3   aliasZaggregate_exprr!   r!   r"   	aggregateJ  s    zQuerySet.aggregatec             C   s2   |  j  d k	 r t |  j   S|  j j d |  j  S)z
        Performs a SELECT COUNT() and returns the number of records as an
        integer.

        If the QuerySet is already fully cached this simply returns the length
        of the cached results set to avoid multiple SELECT COUNT(*) calls.
        Nr(   )rg   r   r3   Z	get_countr2   )r    r!   r!   r"   countf  s    zQuerySet.countc             O   s   |  j  | |   } |  j j   r= |  j j r= | j   } n  t |  } | d k r` | j d S| s |  j j d |  j j	 j
   n  |  j j d |  j j	 j
 | f   d S)zn
        Performs the query and returns a single object matching the given
        keyword arguments.
        r+   r   z!%s matching query does not exist.z2get() returned more than one %s -- it returned %s!N)filterr3   
can_filterr   order_byr   rg   r)   DoesNotExist_metaZobject_nameZMultipleObjectsReturned)r    r   r   r   numr!   r!   r"   r~   s  s    		zQuerySet.getc             K   s5   |  j  |   } d |  _ | j d d d |  j  | S)z
        Creates a new object with the given kwargs, saving it to the database
        and returning the created object.
        TZforce_insertr(   )r)   ri   saver2   )r    r   rK   r!   r!   r"   create  s    	zQuerySet.createc             C   s?   x8 | D]0 } | j  d  k r | j j  j |  | _  q q Wd  S)N)rN   r   Zget_pk_value_on_save)r    objsrK   r!   r!   r"   _populate_pk_values  s    zQuerySet._populate_pk_valuesc             C   s  | d k s | d k s t   xD |  j j j   D]0 } | j j |  j j j k	 r1 t d   q1 q1 W| so | Sd |  _ t |  j } |  j j j	 } t
 |  } |  j |  t j d |  j d d  | j j r |  j j j r |  j | | |  n t d d	   |  \ } } | r1|  j | | |  n  | rd
 d   | D } |  j | | |  } | j j rt |  t |  k st   n  xD t | |  D]0 \ }	 }
 |
 |	 _ d |	 j _ |  j |	 j _ qWn  Wd QX| S)am  
        Inserts each of the instances into the database. This does *not* call
        save() on each of the instances, does not send any pre/post save
        signals, and does not set the primary key attribute if it is an
        autoincrement field (except if features.can_return_ids_from_bulk_insert=True).
        Multi-table models are not supported.
        Nr   z/Can't bulk create a multi-table inherited modelTr(   	savepointFc             S   s   |  j  d  k S)N)rN   )or!   r!   r"   <lambda>  s    z&QuerySet.bulk_create.<locals>.<lambda>c             S   s%   g  |  ] } t  | t  s |  q Sr!   )r   r   )r.   r/   r!   r!   r"   r0     s   	 z(QuerySet.bulk_create.<locals>.<listcomp>)r   r)   r   Zget_parent_listZconcrete_model
ValueErrorri   r   r2   concrete_fieldsrS   r   r
   atomicfeaturesZ6can_combine_inserts_with_and_without_auto_increment_pkZhas_auto_field_batched_insertr   can_return_ids_from_bulk_insertr   rX   rN   _stateZadding)r    r   
batch_sizeparent
connectionrb   Zobjs_with_pkZobjs_without_pkidsZobj_without_pkrN   r!   r!   r"   bulk_create  s8    	!	zQuerySet.bulk_createc             K   sg   |  j  | |  \ } } d |  _ y |  j |   d f SWn( |  j j k
 rb |  j | |  SYn Xd S)z
        Looks up an object with the given kwargs, creating one if necessary.
        Returns a tuple of (object, created), where created is a boolean
        specifying whether an object was created.
        TFN)_extract_model_paramsri   r~   r)   r   _create_object_from_params)r    defaultsr   lookupparamsr!   r!   r"   get_or_create  s    	zQuerySet.get_or_createc       	      K   s   | p	 i  } |  j  | |  \ } } d |  _ y |  j |   } Wn@ |  j j k
 r |  j | |  \ } } | r~ | | f SYn Xx- t j |  D] \ } } t | | |  q W| j	 d |  j
  | d f S)a  
        Looks up an object with the given kwargs, updating one with defaults
        if it exists, otherwise creates a new one.
        Returns a tuple (object, created), where created is a boolean
        specifying whether an object was created.
        Tr(   F)r   ri   r~   r)   r   r   r   	iteritemsr>   r   r2   )	r    r   r   r   r   rK   createdrw   rx   r!   r!   r"   update_or_create  s    	zQuerySet.update_or_createc             C   s   y9 t  j d |  j   |  j |   } Wd QX| d f SWn] t k
 r t j   } y |  j |   d f SWn |  j j	 k
 r Yn Xt
 j |   Yn Xd S)zs
        Tries to create an object using passed params.
        Used by get_or_create and update_or_create
        r(   NTF)r
   r   r2   r   r   sysexc_infor~   r)   r   r   reraise)r    r   r   rK   r   r!   r!   r"   r     s    z#QuerySet._create_object_from_paramsc             K   s   | p	 i  } | j    } xB |  j j j D]1 } | j | k r( | j | j  | | j <q( q( Wd d   | j   D } | j |  | | f S)z
        Prepares `lookup` (kwargs that are valid model attributes), `params`
        (for creating a model instance) based on given kwargs; for use by
        get_or_create and update_or_create.
        c             S   s+   i  |  ]! \ } } t  | k r | |  q Sr!   )r   )r.   rw   rx   r!   r!   r"   
<dictcomp>  s   	 z2QuerySet._extract_model_params.<locals>.<dictcomp>)	rt   r)   r   rb   r-   poprD   r=   r   )r    r   r   r   r/   r   r!   r!   r"   r     s     zQuerySet._extract_model_params-c             C   s   | p t  |  j j d  } t |  s3 t d   |  j j   sN t d   |  j   } | j j d d  | j j	 d d  | j j
 d | | f  | j   S)	z
        Returns the latest object, according to the model's
        'get_latest_by' option or optional given field_name.
        Zget_latest_byz]earliest() and latest() require either a field_name parameter or 'get_latest_by' in the modelz2Cannot change a query once a slice has been taken.highr+   force_emptyTz%s%s)rB   r)   r   r   r   r3   r   r   r   clear_orderingadd_orderingr~   )r    
field_name	directionr   rK   r!   r!   r"   _earliest_or_latest  s    	zQuerySet._earliest_or_latestc             C   s   |  j  d | d d  S)Nr   r    )r   )r    r   r!   r!   r"   earliest"  s    zQuerySet.earliestc             C   s   |  j  d | d d  S)Nr   r   r   )r   )r    r   r!   r!   r"   latest%  s    zQuerySet.latestc             C   s@   t  |  j r |  n |  j d  d d   } | r< | d Sd S)zY
        Returns the first object of a query, returns None if no match is found.
        rN   Nr+   r   )rS   orderedr   )r    objectsr!   r!   r"   first(  s    .zQuerySet.firstc             C   sF   t  |  j r |  j   n |  j d  d d   } | rB | d Sd S)zX
        Returns the last object of a query, returns None if no match is found.
        z-pkNr+   r   )rS   r   reverser   )r    r   r!   r!   r"   last1  s    4zQuerySet.lastc             C   si   |  j  j   s t d   | d k	 rL | s1 i  S|  j d |  j   } n |  j   } d d   | D S)z
        Returns a dictionary mapping each of the given IDs to the object with
        that ID. If `id_list` isn't provided, the entire QuerySet is evaluated.
        z+Cannot use 'limit' or 'offset' with in_bulkNZpk__inc             S   s   i  |  ] } | | j     q Sr!   )Z_get_pk_val)r.   rK   r!   r!   r"   r   G  s   	 z$QuerySet.in_bulk.<locals>.<dictcomp>)r3   r   r   r   r   r   )r    Zid_listr   r!   r!   r"   in_bulk:  s    	zQuerySet.in_bulkc             C   s   |  j  j   s t d   |  j d k	 r9 t d   n  |  j   } d | _ d | j  _ d | j  _ | j  j	 d d  t
 d | j  } | j |  | j   \ } } d |  _ | | f S)z>
        Deletes the records in the current QuerySet.
        z+Cannot use 'limit' or 'offset' with delete.Nz6Cannot call delete() after .values() or .values_list()TFr   r(   )r3   r   r   r^   r   r   ri   select_for_updateselect_relatedr   r   r2   Zcollectdeleterg   )r    Z	del_queryZ	collectorZdeletedZ_rows_countr!   r!   r"   r   I  s    			zQuerySet.deletec             C   s   t  j |  j  j |  |  S)z
        Deletes objects found from the given queryset in single direct SQL
        query. No signals are sent, and there is no protection for cascades.
        )r   ZDeleteQueryr)   Z	delete_qs)r    r(   r!   r!   r"   _raw_deletej  s    zQuerySet._raw_deletec          	   K   s   |  j  j   s t d   d |  _ |  j  j t j  } | j |  t j	 d |  j
 d d    | j |  j
  j t  } Wd QXd |  _ | S)z
        Updates all elements in the current QuerySet, setting all the given
        fields to the appropriate values.
        z2Cannot update a query once a slice has been taken.Tr(   r   FN)r3   r   r   ri   r   r   UpdateQueryZadd_update_valuesr
   r   r2   r4   r5   r   rg   )r    r   r3   rowsr!   r!   r"   r   r  s    		!	zQuerySet.updatec             C   s_   |  j  j   s t d   |  j  j t j  } | j |  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)r3   r   r   r   r   r   Zadd_update_fieldsrg   r4   r2   r5   r   )r    valuesr3   r!   r!   r"   _update  s    		zQuerySet._updateFc             C   s2   |  j  d  k r% |  j j d |  j  St |  j   S)Nr(   )rg   r3   Zhas_resultsr2   r   )r    r!   r!   r"   exists  s    zQuerySet.existsc             C   s    t  |  j |  j  d |  _ d  S)NT)prefetch_related_objectsrg   rj   rk   )r    r!   r!   r"   _prefetch_related_objects  s    z"QuerySet._prefetch_related_objectsc          
   C   s=   | d  k r |  j  } n  t | d |  j d | d | d | S)Nr)   r   translationsr(   )r2   RawQuerySetr)   )r    	raw_queryr   r   r(   r!   r!   r"   raw  s    zQuerySet.rawc             G   s}  |  j    } | | _ | j } d | _ | j   | j   | j d k r | j d d   |  j j	 j
 D d  | j   | j   n  | rDg  } g  } g  } | j r | j r t |  } ne d | _ xY | D]Q } | | j k r | j |  q | | j k r| j |  q | j |  q W| j |  | j |  n d d   |  j j	 j
 D } | | _ | j | d  | S)NFTc             s   s   |  ] } | j  Vq d  S)N)r-   )r.   r/   r!   r!   r"   r`     s    z#QuerySet._values.<locals>.<genexpr>c             S   s   g  |  ] } | j   q Sr!   )r-   )r.   r/   r!   r!   r"   r0     s   	 z$QuerySet._values.<locals>.<listcomp>)r   r^   r3   r   clear_deferred_loadingZclear_select_fieldsgroup_byZ
add_fieldsr)   r   r   set_group_byZ_extraZ_annotationsrS   Zdefault_colsrU   appendrV   Zset_extra_maskZset_annotation_maskrT   )r    rb   r   r3   rY   rZ   r[   r/   r!   r!   r"   _values  s:    			

&
		zQuerySet._valuesc             G   s   |  j  |   } t | _ | S)N)r  rR   rl   )r    rb   r   r!   r!   r"   r     s    	zQuerySet.valuesc             O   s   | j  d d  } | r4 t d t |  f   n  | r[ t |  d k r[ t d   n  |  j |   } | rv t n t | _ | S)NflatFz/Unexpected keyword arguments to values_list: %sr+   zH'flat' is not valid when values_list is called with more than one field.)r   r   rS   r   r  rc   r]   rl   )r    rb   r   r  r   r!   r!   r"   values_list  s    zQuerySet.values_listASCc             C   s   | d k s t  d   | d k s0 t  d   |  j d t | | d	 t   d
 t |   j d d d j   j d d  j | d k r d n d d  S)z
        Returns a list of date objects representing all available dates for
        the given field_name, scoped to 'kind'.
        yearmonthdayz/'kind' must be one of 'year', 'month' or 'day'.r  DESCz''order' must be either 'ASC' or 'DESC'.Z	datefieldoutput_fieldplain_fieldr  Tplain_field__isnullFr   r   )zyearzmonthzday)r  r  )	r   annotater   r   r   r  distinctr   r   )r    r   kindorderr!   r!   r"   dates  s    			zQuerySet.datesc          	   C   s   | d k s t  d   | d k s0 t  d
   t j rW | d k r] t j   } q] n d } |  j d t | | d t   d | d t |   j	 d d d j
   j d d  j | d	 k r d n d d  S)z
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        r  r  r  hourminutesecondzK'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'.r  r  z''order' must be either 'ASC' or 'DESC'.NZdatetimefieldr	  tzinfor
  r  Tr  Fr   r   )zyearzmonthzdayzhourzminutezsecond)zASCzDESC)r   r   ZUSE_TZr   Zget_current_timezoner  r   r   r   r  r  r   r   )r    r   r  r  r  r!   r!   r"   	datetimes  s    				zQuerySet.datetimesc             C   s   |  j    } | j j   | S)z,
        Returns an empty QuerySet.
        )r   r3   Z	set_empty)r    r   r!   r!   r"   none  s    zQuerySet.nonec             C   s
   |  j    S)z
        Returns 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 | |  S)zb
        Returns a new QuerySet instance with the args ANDed to the existing
        set.
        F)_filter_or_exclude)r    r   r   r!   r!   r"   r     s    zQuerySet.filterc             O   s   |  j  d | |  S)zd
        Returns a new QuerySet instance with NOT (args) ANDed to the existing
        set.
        T)r  )r    r   r   r!   r!   r"   exclude  s    zQuerySet.excludec             O   sv   | s | r* |  j  j   s* t d   n  |  j   } | rY | j  j t | |    n | j  j t | |    | S)Nz2Cannot filter a query once a slice has been taken.)r3   r   r   r   add_qr   )r    negater   r   r   r!   r!   r"   r  %  s    zQuerySet._filter_or_excludec             C   sR   t  | t  s t | d  r> |  j   } | j j |  | S|  j d |  Sd S)ao  
        Returns a new QuerySet instance with filter_obj added to the filters.

        filter_obj can be a Q object (or anything with an add_to_query()
        method) 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.
        Zadd_to_queryN)r   r   r@   r   r3   r  r  )r    Z
filter_objr   r!   r!   r"   complex_filter1  s
    
zQuerySet.complex_filterc             C   s1   |  j    } d | _ d | j _ | | j _ | S)zj
        Returns a new QuerySet instance that will select objects with a
        FOR UPDATE lock.
        T)r   ri   r3   r   Zselect_for_update_nowait)r    ZnowaitrK   r!   r!   r"   r   B  s
    	zQuerySet.select_for_updatec             G   sn   |  j  d k	 r t d   n  |  j   } | d k rE d | j _ n% | r^ | j j |  n d | j _ | S)a  
        Returns 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, the list is cleared.
        Nz>Cannot call select_related() after .values() or .values_list()FT)N)r^   r   r   r3   r   Zadd_select_related)r    rb   rK   r!   r!   r"   r   M  s    
zQuerySet.select_relatedc             G   s8   |  j    } | d k r$ g  | _ n | j j |  | S)ad  
        Returns 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, the list of lookups to
        prefetch is appended to. If prefetch_related(None) is called, the list
        is cleared.
        N)N)r   rj   extend)r    lookupsr   r!   r!   r"   prefetch_relatedc  s
    
zQuerySet.prefetch_relatedc       	      O   s  t    } xk | D]c } y) | j | k r> t d | j   n  Wn$ t t f k
 re t d   Yn X| | | j <q W| j |  |  j   } |  j } | d k r d d   |  j j	 j
   D } n  xR | j   D]D \ } } | | k r t d |   n  | j j | | d d q Wxd | j j j   D]P \ } } | | k r/| j r/| j d k rnd	 | j _ n | j j   Pq/q/W| S)
z
        Return a query set in which the returned objects have been annotated
        with extra data or aggregations.
        zQThe named annotation '%s' conflicts with the default name for another annotation.z$Complex annotations require an aliasNc             S   s   h  |  ] } | j   q Sr!   )rD   )r.   r/   r!   r!   r"   	<setcomp>  s   	 z$QuerySet.annotate.<locals>.<setcomp>z8The annotation '%s' conflicts with a field on the model.r   FT)r   r   r   r   r   r   r   r^   r)   r   Z
get_fieldsr=   r3   r   r   r   r   r   )	r    r   r   r   r   r   r\   r   Z
annotationr!   r!   r"   r  t  s4    		"zQuerySet.annotatec             G   sN   |  j  j   s t d   |  j   } | j  j d d  | j  j |   | S)zL
        Returns a new QuerySet instance with the ordering changed.
        z3Cannot reorder a query once a slice has been taken.r   F)r3   r   r   r   r   r   )r    rY   rK   r!   r!   r"   r     s    	zQuerySet.order_byc             G   s;   |  j  j   s t d   |  j   } | j  j |   | S)zY
        Returns a new QuerySet instance that will select only distinct results.
        z:Cannot create distinct fields once a slice has been taken.)r3   r   r   r   Zadd_distinct_fields)r    rY   rK   r!   r!   r"   r    s
    	zQuerySet.distinctc             C   sJ   |  j  j   s t d   |  j   } | j  j | | | | | |  | S)z8
        Adds extra SQL fragments to the query.
        z1Cannot change a query once a slice has been taken)r3   r   r   r   Z	add_extra)r    r6   wherer   Ztablesr   Zselect_paramsr   r!   r!   r"   extra  s
    	zQuerySet.extrac             C   s#   |  j    } | j j | j _ | S)z8
        Reverses the ordering of the QuerySet.
        )r   r3   Zstandard_ordering)r    r   r!   r!   r"   r     s    zQuerySet.reversec             G   sZ   |  j  d k	 r t d   n  |  j   } | d k rF | j j   n | j j |  | S)aU  
        Defers the loading of data for certain fields until they are accessed.
        The set of fields to defer is added 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 all deferrals are removed (None acts as a
        reset option).
        Nz5Cannot call defer() after .values() or .values_list())N)r^   r   r   r3   r   Zadd_deferred_loading)r    rb   r   r!   r!   r"   defer  s    zQuerySet.deferc             G   sY   |  j  d k	 r t d   n  | d k r9 t d   n  |  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.
        Nz4Cannot call only() after .values() or .values_list()z*Cannot pass None as an argument to only().)N)r^   r   r   r3   Zadd_immediate_loading)r    rb   r   r!   r!   r"   only  s    zQuerySet.onlyc             C   s   |  j    } | | _ | S)zX
        Selects which database this QuerySet should execute its query against.
        )r   re   )r    r   r   r!   r!   r"   r(     s    	zQuerySet.usingc             C   sF   |  j  j s |  j  j r d S|  j  j r> |  j  j   j r> d Sd Sd S)z
        Returns True if the QuerySet is ordered -- i.e. has an order_by()
        clause or a default ordering on the model.
        TFN)r3   Zextra_order_byr   Zdefault_orderingZget_metaZordering)r    r!   r!   r"   r     s
    zQuerySet.orderedc             C   sG   |  j  r( |  j p' t j |  j |  j  S|  j pF t j |  j |  j  S)zCReturn the database that will be used if this query is executed now)ri   re   r	   Zdb_for_writer)   rf   db_for_read)r    r!   r!   r"   r2      s    	zQuerySet.dbc             C   sb   d |  _  | d k r! |  j } n  t j |  j  } | j | | d | | j d |  j |  S)z
        Inserts a new record for the given model. This provides an interface to
        the InsertQuery class and is how Model.save() is implemented.
        TNr   r(   )ri   r2   r   ZInsertQueryr)   Zinsert_valuesr4   r5   )r    r   rb   	return_idr   r(   r3   r!   r!   r"   _insert  s    	zQuerySet._insertc          	      s   s
 d St  |  j j }   p8 t | j |   d    g  } x    f d d   t d t      D D] } t  |  j j j r |  j	 | d | d |  j d d	 } t   d k r | j
 |  n  t   d k r| j |  qqp |  j	 | d | d |  j qp W| S)
z
        A little helper method for bulk_insert to insert the bulk one batch
        at a time. Inserts recursively a batch from the front of the bulk and
        then _batched_insert() the remaining objects again.
        Nr+   c                s$   g  |  ] }  | |     q Sr!   r!   )r.   i)r   r   r!   r"   r0   $  s   	 z,QuerySet._batched_insert.<locals>.<listcomp>r   rb   r(   r&  T)r   r2   opsmaxZbulk_batch_sizeranger   r   r   r'  r  r   )r    r   rb   r   r)  Zinserted_idsitemZinserted_idr!   )r   r   r"   r     s    !5$ zQuerySet._batched_insertc          	   K   s   |  j  j   } |  j r$ d | _ n  |  j d |  j d | d |  j d |  j  } |  j | _ |  j	 d  d   | _	 |  j
 | _
 |  j | _ |  j | _ | j j |  | S)NTr)   r3   r(   rm   )r3   r   rh   Zfilter_is_stickyrr   r)   re   rf   ri   rj   r?   rl   r^   rs   r   )r    r   r3   r   r!   r!   r"   r   /  s    	-zQuerySet._clonec             C   sK   |  j  d  k r' t |  j    |  _  n  |  j rG |  j rG |  j   n  d  S)N)rg   rS   r   rj   rk   r   )r    r!   r!   r"   rz   =  s    zQuerySet._fetch_allc             C   s   d |  _  |  S)a  
        Indicates 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)rh   )r    r!   r!   r"   _next_is_stickyC  s    	zQuerySet._next_is_stickyc             C   s   |  j  d k	 r t |  j j  t | j j  k s{ t |  j j  t | j j  k s{ t |  j j  t | j j  k r t d |  j j   n  d S)zM
        Checks that we are merging two comparable QuerySet classes.
        Nz?Merging '%s' classes must involve the same values in each case.)	r^   setr3   rT   rU   rV   r   rr   r$   )r    r   r!   r!   r"   r   Q  s    $$$zQuerySet._merge_sanity_checkc             C   s@   x9 | j  j   D]( \ } } |  j  j | i   j |  q Wd S)zX
        Keep track of all known related objects from either QuerySet instance.
        N)r?   r=   
setdefaultr   )r    r   rM   r   r!   r!   r"   r   ^  s    z%QuerySet._merge_known_related_objectsc             C   s   |  j  d  k	 rE t |  j  p' |  j j j  d k r t d   q n[ |  j | j k r t | d f   } t |  d k r | d j r |  j | d j	  Sn  |  S)Nr+   z0Cannot use multi-field values as a filter value.Zforeign_related_fieldsr   )
r^   r   r)   r   r   r   rB   Zprimary_keyr   rD   )r    rM   Zforeign_fieldsr!   r!   r"   _preparee  s    $ zQuerySet._preparec             C   s   |  j  d k	 rQ t |  j  p' |  j j j  d k rB t d   n  |  j   } n |  j d  } | j d k s | t	 | j k r | j
 j d |  j   St d   d S)zO
        Returns the internal query's SQL and parameters (as a tuple).
        Nr+   z0Cannot use multi-field values as a filter value.rN   r   z2Can't do subqueries with queries on different DBs.)r^   r   r)   r   r   r   r   r   re   r   r3   r4   Zas_nested_sqlr   )r    r   r   r!   r!   r"   _as_sqls  s    $"zQuerySet._as_sqlc             K   s   |  j  j |  d S)zE
        Update hinting information for later use by Routers
        N)rf   r   )r    rm   r!   r!   r"   
_add_hints  s    zQuerySet._add_hintsc             C   s   |  j  j   S)z
        Checks if this QuerySet has any filtering going on. Note that this
        isn't equivalent for checking if all objects are present in results,
        for example qs[1:]._has_filters() -> False.
        )r3   Zhas_filters)r    r!   r!   r"   _has_filters  s    zQuerySet._has_filtersc             C   s&   |  j  d k	 r d St |  j | |  S)a  
        Check that using this queryset as the rhs value for a lookup is
        allowed. The opts are the options of the relation's target we are
        querying against. For example in .filter(author__in=Author.objects.all())
        the opts would be Author's (from the author field) and self.model would
        be Author.objects.all() queryset's .model (Author also). The field is
        the related field on the lhs side.
        NT)r^   r   r)   )r    optsrM   r!   r!   r"   is_compatible_query_object_type  s    
z(QuerySet.is_compatible_query_object_type)Rr$   r%   r&   rQ   r#   rq   Zqueryset_onlyclassmethodry   r{   r   r   r   rP   r   r   r   r   r   r   r   r   r~   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   r  r  r  r   r   r  r  r   r  r"  r   r#  r$  r(   r   propertyr2   r'  r   r   rz   r-  r   r   r0  r1  Zvalue_annotationr2  r3  r5  r!   r!   r!   r"   rd      s   	

7									)*

		rd   c               @   s   e  Z d  Z d d   Z d S)InstanceCheckMetac             C   s   t  | t  o | j j   S)N)r   rd   r3   Zis_empty)r    instancer!   r!   r"   __instancecheck__  s    z#InstanceCheckMeta.__instancecheck__N)r$   r%   r&   r:  r!   r!   r!   r"   r8    s   r8  c               @   s"   e  Z d  Z d Z d d   Z d S)r   z
    Marker class usable for 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&   rQ   r#   r!   r!   r!   r"   r     s   r   c               @   s   e  Z d  Z d Z d d d d d d 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)r   zp
    Provides an iterator which converts the results of raw SQL queries into
    annotated model instances.
    Nc             C   sv   | |  _  | |  _ | |  _ | p$ i  |  _ | pN t j d | d |  j d |  |  _ | p] f  |  _ | pl i  |  _	 d  S)Nr   r(   r   )
r   r)   re   rf   r   ZRawQueryr2   r3   r   r   )r    r   r)   r3   r   r   r(   rm   r!   r!   r"   r#     s    			*zRawQuerySet.__init__c                s}     f d d     j  j j D }   f d d   t   j  D }   f d d   | D } d d   | D } | | | f S)zB
        Resolve the init field names and value positions
        c                s(   g  |  ] } | j    j k r |  q Sr!   )columncolumns)r.   r/   )r    r!   r"   r0     s   	 z8RawQuerySet.resolve_model_init_order.<locals>.<listcomp>c                s1   g  |  ]' \ } } |   j  k r | | f  q Sr!   )model_fields)r.   posr;  )r    r!   r"   r0     s   	 	c                s%   g  |  ] }   j  j | j   q Sr!   )r<  indexr;  )r.   r/   )r    r!   r"   r0     s   	 c             S   s   g  |  ] } | j   q Sr!   )r-   )r.   r/   r!   r!   r"   r0     s   	 )r)   r   rb   	enumerater<  )r    Zmodel_init_fieldsannotation_fieldsZmodel_init_ordermodel_init_namesr!   )r    r"   resolve_model_init_order  s
    ""z$RawQuerySet.resolve_model_init_orderc             #   s    j  } t | j j d    j t | |  } t   j  } zb  j   \ } } } t   } x9   j j	 j
 D]( } | j | k rr | j | j  qr qr W| r   j j	 j j | k r t d   q n    j }	   f d d     j D }
 | j d d   |
 D  } x | D]  | r7| j  |   n   f d d   | D } |	 j | | |  } | rx+ | D]  \ } } t | |  |  qrWn  | VqWWd  t   j d  r  j j r  j j j   n  Xd  S)NZSQLCompilerz&Raw query must include the primary keyc                s"   g  |  ] }   j  j |   q Sr!   )r=  r~   )r.   c)r    r!   r"   r0     s   	 z(RawQuerySet.__iter__.<locals>.<listcomp>c             S   s4   g  |  ]* } | r* | j  | j j j  n d   q S)N)Zget_colr)   r   Zdb_table)r.   r/   r!   r!   r"   r0     s   	 c                s   g  |  ] }   |  q Sr!   r!   )r.   r>  )r   r!   r"   r0     s   	 cursor)r2   r   r)  rE   r3   r   rC  r.  r)   r   rb   r-   addrN   r   r<  Zget_convertersZapply_convertersr;   r>   r@   rE  close)r    r2   rE   r3   rB  Zmodel_init_posrA  skiprM   rG   rb   Z
convertersZmodel_init_valuesr9  r;  r>  r!   )r    r   r"   rP     s8    			zRawQuerySet.__iter__c             C   s   d |  j  S)Nz<RawQuerySet: %s>)r3   )r    r!   r!   r"   r     s    zRawQuerySet.__repr__c             C   s   t  |   | S)N)rS   )r    rw   r!   r!   r"   r     s    zRawQuerySet.__getitem__c             C   s   |  j  p t j |  j |  j  S)zCReturn the database that will be used if this query is executed now)re   r	   r%  r)   rf   )r    r!   r!   r"   r2     s    zRawQuerySet.dbc             C   sC   t  |  j d |  j d |  j j d |  d |  j d |  j d | S)z\
        Selects which database this Raw QuerySet should execute its query against.
        r)   r3   r(   r   r   )r   r   r)   r3   r   r   r   )r    r   r!   r!   r"   r(     s
    zRawQuerySet.usingc             C   s   t  |  d  s| |  j j   |  _ xX |  j j   D]D \ } } y# |  j j |  } | |  j | <Wq1 t k
 rt Yq1 Xq1 Wn  |  j S)zg
        A list of model field names in the order they'll appear in the
        query results.
        _columns)r@   r3   Zget_columnsrI  r   r=   r?  r   )r    Z
query_nameZ
model_namer?  r!   r!   r"   r<    s    zRawQuerySet.columnsc             C   st   t  |  d  sm t |  j j j } i  |  _ x? |  j j j D]+ } | j	   \ } } | |  j | |  <q; Wn  |  j S)zC
        A dict mapping column names to model field names.
        _model_fields)
r@   r   r2   ZintrospectionZtable_name_converterrJ  r)   r   rb   Zget_attname_column)r    	converterrM   rD   r;  r!   r!   r"   r=  #  s    	zRawQuerySet.model_fields)r$   r%   r&   rQ   r#   rC  rP   r   r   r7  r2   r(   r<  r=  r!   r!   r!   r"   r     s   		(r   c               @   sv   e  Z d  Z d 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)PrefetchNc             C   s   | |  _  | |  _ | d  k	 r< | j t k	 r< t d   n  | rq t j | j t  d  d  | g  |  _ n  | |  _ | |  _	 d  S)Nz'Prefetch querysets cannot use values().r+   r1   )
prefetch_throughprefetch_torl   r'   r   r   joinsplitr   to_attr)r    r   r   rQ  r!   r!   r"   r#   2  s    		/	zPrefetch.__init__c             C   s:   t  j | |  j g  |  _ t  j | |  j g  |  _ d  S)N)r   rO  rM  rN  )r    prefixr!   r!   r"   
add_prefix?  s    zPrefetch.add_prefixc             C   s'   t  j |  j j t   d  | d   S)Nr+   )r   rO  rM  rP  )r    levelr!   r!   r"   get_current_prefetch_throughC  s    z%Prefetch.get_current_prefetch_throughc             C   s'   t  j |  j j t   d  | d   S)Nr+   )r   rO  rN  rP  )r    rT  r!   r!   r"   get_current_prefetch_toF  s    z Prefetch.get_current_prefetch_toc             C   sE   |  j  j t  } | | } |  j o8 | t |  d k } | | f S)Nr+   )rN  rP  r   rQ  r   )r    rT  partsrQ  as_attrr!   r!   r"   get_current_to_attrI  s    
zPrefetch.get_current_to_attrc             C   s#   |  j  |  |  j k r |  j Sd  S)N)rV  rN  r   )r    rT  r!   r!   r"   get_current_querysetO  s    zPrefetch.get_current_querysetc             C   s#   t  | t  r |  j | j k Sd S)NF)r   rL  rN  )r    r   r!   r!   r"   __eq__T  s    zPrefetch.__eq__c             C   s   t  |  j  t  |  j  AS)N)hashrr   rN  )r    r!   r!   r"   __hash__Y  s    zPrefetch.__hash__)r$   r%   r&   r#   rS  rU  rV  rY  rZ  r[  r]  r!   r!   r!   r"   rL  1  s   rL  c             C   s\   g  } xO |  D]G } t  | t  s1 t |  } n  | rG | j |  n  | j |  q W| S)zG
    Helper function that normalize lookups into Prefetch objects.
    )r   rL  rS  r   )r  rR  retr   r!   r!   r"   normalize_prefetch_lookups]  s    r_  c             G   s"  t  |   d k r d St |  } i  } t   } t   } t |  } x| r| j   } | j | k r | j rI t d | j   qI qI n  |  } | j j	 t
  } xpt |  D]b\ }	 }
 t  |  d k r Pn  | j |	  } | | k r| | } q n  d } xO | D]G } t | d  sy i  | _ WqUt t f k
 rQd } PYqUXqqW| scPn  | d } | j |	  d } t | |
 |  \ } } } } | st d |
 | j j | j f   n  |	 t  |  d k r| d k rt d	 | j   n  | d k	 r| rt | | | |	  \ } } | | k oD| | k s}| | | <t | |  } | j |  | j |  n  | j |  q g  } xz | D]r } y t | |
  } Wn t j k
 rwYn X| d k rqn  t | t  r| j |  q| j |  qW| } q WqI Wd S)
z|
    Populate prefetched object caches for a list of model instances based on
    the lookups/Prefetch instances given.
    r   Nzl'%s' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups.T_prefetched_objects_cacheFzQCannot find '%s' on %s object, '%s' is an invalid parameter to prefetch_related()r+   zp'%s' does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().) r   r_  r.  r   popleftrN  r   r   rM  rP  r   r@  rV  r@   r`  r   r   rY  get_prefetcherrr   r$   prefetch_one_levelr   
extendleftrF  rB   r   ZObjectDoesNotExistr   rS   r  r   )Zmodel_instancesZrelated_lookupsZdone_queriesZauto_lookupsZfollowed_descriptorsZall_lookupsr   Zobj_listZthrough_attrsrT  through_attrrN  Zgood_objectsrK   Z	first_objrQ  
prefetcherZ
descriptor
attr_found
is_fetchedadditional_lookupsZnew_lookupsZnew_obj_listZnew_objr!   r!   r"   r   k  s|    				

"
	r   c             C   s  d } d } t  |  j | d  } | d k r? t |  |  } n d } | rt | d  r{ | } | j |   r d } q qt  |  |  } t | d  r | } n  | | k r t t  |  j | d  t  r | |  j k } q t |  |  } q| |  j k } n  | | | | f S)a  
    For the attribute 'through_attr' on the given instance, finds
    an object that has a get_prefetch_queryset().
    Returns 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 boolean that is True if the attribute has already been fetched)
    NFTget_prefetch_queryset)rB   rr   r@   Z	is_cachedr   r   rs   r`  )r9  re  rQ  rf  rh  Zrel_obj_descriptorrg  rO   r!   r!   r"   rb    s(    
	rb  c             C   s  | j  |  | j |   \ } } } } } d d   t | d g   D }	 |	 r[ g  | _ n  t |  }
 i  } x3 |
 D]+ } | |  } | j | g   j |  qt W| j |  \ } } | r!|  r!|  d j } y | j	 j
 |  Wn t j k
 r Yq!Xd } t | j | | j    n  t | j j t   d | k } x;|  D]3} | |  } | j | g   } | r| r| d n d } | r| n | } t | | |  qJ| rt | | |  qJt | |  } | rR| j d k	 rRy | j } WnD t k
 r?t j d | j j | j j f t  | j   } Yq^X| | j  } n | j   } | | _ d	 | _ | | j  | <qJW|
 |	 f S)
aU  
    Helper function for prefetch_related_objects

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

    The prefetched objects are returned, 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 Sr!   )rt   )r.   Zadditional_lookupr!   r!   r"   r0   5  s   	 z&prefetch_one_level.<locals>.<listcomp>rj   r   z2to_attr={} conflicts with a field on the {} model.r+   NzThe `%s.%s` class must implement a `_apply_rel_filters()` method that accepts a `QuerySet` as its single argument and returns an appropriately filtered version of it.T)!rj  rZ  rB   rj   rS   r/  r   rY  rr   r   	get_fieldr   ZFieldDoesNotExistr   formatr$   r   rM  rP  r   r~   r>   r   Z_apply_rel_filtersr   r   r   r%   r   Zget_querysetrg   rk   r`  )Z	instancesrf  r   rT  Zrel_qsZrel_obj_attrZinstance_attrZsingle
cache_nameri  Zall_related_objectsZrel_obj_cacherO   Zrel_attr_valrQ  rX  r)   r   ZleafrK   Zinstance_attr_valvalsvalrp   Zapply_rel_filterr   r!   r!   r"   rc    sZ    *	"		rc  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 } | ss | d |  _ | d d |  _ d d   | |  j |  j  D |  _ d  |  _ n d d   | d j j D } g  } xJ | D]B } | | d j }	 | j |	 j	  }
 | j
 |
 |	 j	 | f  q W| j   d	 d   | D |  _ d
 d   | D     f d d   } | |  _ | d |  _ |  j j |  j j j j	  |  _ t | | |  j   |  _ | d }	 | d } d  |  _ | r|	 j j   |  _ |	 j   |  _ n- |	 j   |  _ |	 j r|	 j j   |  _ n  d  S)Nr*   from_parentr   r+   c             S   s    g  |  ] } | d  j  j  q S)r   )r,   r-   )r.   r/   r!   r!   r"   r0     s   	 z-RelatedPopulator.__init__.<locals>.<listcomp>c             S   s   g  |  ] } | j   q Sr!   )r-   )r.   r/   r!   r!   r"   r0     s   	 r)   c             S   s   g  |  ] } | d   q S)r+   r!   )r.   rx   r!   r!   r"   r0     s   	 c             S   s   g  |  ] \ } } } |  q Sr!   r!   )r.   _row_posr!   r!   r"   r0     s   	 c                s     f d d    D S)Nc                s   g  |  ] }   |  q Sr!   r!   )r.   rs  )rJ   r!   r"   r0     s   	 zGRelatedPopulator.__init__.<locals>.reorder_for_init.<locals>.<listcomp>r!   )rJ   )pos_list)rJ   r"   reorder_for_init  s    z3RelatedPopulator.__init__.<locals>.reorder_for_initrM   r   r1   )r2   
cols_startcols_endrH   ru  r   r   r,   r?  r-   r   sortrG   rN   pk_idxr9   rI   reverse_cache_nameZremote_fieldrA   rm  unique)r    r7   r6   r2   r*   rq  Zmodel_init_attnamesZreorder_mapidxrM   Zinit_posru  r   r!   )rt  r"   r#     s>    	

&
	!

		zRelatedPopulator.__init__c             C   s   |  j  r |  j  |  } n | |  j |  j  } | |  j d  k rM d  } n |  j j |  j |  j |  } | r |  j r x$ |  j D] } | j	 | |  q Wn  t
 | |  j |  | r |  j r t
 | |  j |  n  d  S)N)ru  rv  rw  ry  rG   r;   r2   rH   rI   r<   r>   rm  rz  )r    rJ   Zfrom_objZobj_datarK   Zrel_iterr!   r!   r"   r<     s    		zRelatedPopulator.populateN)r$   r%   r&   rQ   r#   r<   r!   r!   r!   r"   rp  {  s   Arp  c             C   sL   g  } |  j  d g   } x- | D]% } t | | |  } | j |  q W| S)Nrelated_klass_infos)r~   rp  r   )r7   r6   r2   	iteratorsr}  Zrel_klass_infoZrel_clsr!   r!   r"   r9     s    r9   )DrQ   rt   r   r   collectionsr   r   Zdjango.confr   Zdjango.corer   Z	django.dbr   r   r   r	   r
   Zdjango.db.modelsr   r   r   Zdjango.db.models.constantsr   Zdjango.db.models.deletionr   Zdjango.db.models.expressionsr   Zdjango.db.models.fieldsr   Zdjango.db.models.functionsr   Zdjango.db.models.query_utilsr   r   r   Zdjango.db.models.sql.constantsr   Zdjango.utilsr   r   Zdjango.utils.deprecationr   Zdjango.utils.functionalr   r   Zdjango.utils.versionr   r   ZEmptyResultSetobjectr   r'   rR   r]   rc   rd   r   r8  with_metaclassr   r   rL  r_  r   rb  rc  rp  r9   r!   r!   r!   r"   <module>   sR   (	0!    
z,{/fa