

_V>d                 @   s  d  d l  m Z d  d l Z d  d l m Z d  d l m Z d  d l m Z d  d l	 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 m Z d  d l m Z d  d l m Z d  d l 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 d  Z' d d   Z( Gd d   d e)  Z* Gd d   d e  Z+ Gd d   d e
  Z, Gd d    d  e)  Z- d S)!    )unicode_literalsN)OrderedDict)contextmanager)	AppConfig)Appsapps)settings)models)OrderWrt)RECURSIVE_RELATIONSHIP_CONSTANT)DEFAULT_NAMESnormalize_together)make_model_tuple)six)
force_text
smart_text)cached_property)import_string)get_docs_version   )InvalidBasesError c             C   sh   t  |  t j  rN |  j d d  } t |  d k r@ t |  S| | d f S|  j j |  j j f Sd  S)N.r      r   )	
isinstancer   string_typessplitlentuple_meta	app_label
model_name)modelr    r    r#   </tmp/pip-build-ghmbqnp_/Django/django/db/migrations/state.py_get_app_label_and_model_name   s    *r%   c             C   s   d d   } t    } | |   } xe | D]] } | j j | j j } } | | f | k r_ q( n  | j | | f  | j | |   q( W| |  j j |  j j f h S)a  
    Returns all models that have a direct or indirect relationship
    to the given model.

    Relationships are either defined by explicit relational fields, like
    ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another
    model (a superclass is related to its subclasses, but not vice versa). Note,
    however, that a model inheriting from a concrete model is also related to
    its superclass through the implicit *_ptr OneToOneField on the subclass.
    c             S   s=   d d   |  j  j d d d d  D d d   |  j   D S)Nc             S   sG   g  |  ]= } | j  r | j d  k	 r t | j t j  r | j  q S)N)is_relationrelated_modelr   r   r   ).0fr#   r#   r$   
<listcomp>-   s   	 zIget_related_models_recursive.<locals>._related_models.<locals>.<listcomp>Zinclude_parentsTZinclude_hiddenc             S   s(   g  |  ] } t  | t j  r |  q Sr#   )
issubclassr	   Model)r(   subclassr#   r#   r$   r*   0   s   	 )r   Z
get_fields__subclasses__)mr#   r#   r$   _related_models+   s    %z5get_related_models_recursive.<locals>._related_models)setr   r    r!   addextend)r"   r0   seenqueueZrel_modrel_app_labelrel_model_namer#   r#   r$   get_related_models_recursive    s    		r8   c               @   s   e  Z d  Z d Z d d d d  Z d d   Z d d   Z d	 d
   Z d d   Z e	 d d    Z
 e d d    Z e d d    Z d d   Z d d   Z d S)ProjectStatez
    Represents the entire project's overall state.
    This is the item that is passed around - we do it here rather than at the
    app level so that cross-app FKs/etc. resolve properly.
    Nc             C   s"   | p	 i  |  _  | p g  |  _ d  S)N)r	   	real_apps)selfr	   r:   r#   r#   r$   __init__F   s    zProjectState.__init__c             C   sL   | j  | j } } | |  j | | f <d |  j k rH |  j | |  n  d  S)Nr   )r    
name_lowerr	   __dict__reload_model)r;   model_stater    r!   r#   r#   r$   	add_modelK   s    zProjectState.add_modelc             C   sF   |  j  | | f =d |  j k rB |  j j | |  |  j j   n  d  S)Nr   )r	   r>   r   unregister_modelclear_cache)r;   r    r!   r#   r#   r$   remove_modelQ   s    zProjectState.remove_modelc             C   sA  d |  j  k r=y |  j j | |  } Wn t k
 rE t   } Yn Xt |  } |  j | | f } t   } xl | j D]a \ } } | j rx | j	 j
 t k r qx n  t | j |  \ }	 }
 | j |	 |
 j   f  qx qx W| j |  xU | D]M \ }	 }
 y |  j j |	 |
  } Wn t k
 r*Yq X| j t |   q W| j | | f  |  j j   / x' | D] \ }	 }
 |  j j |	 |
  qlWWd  QXg  } x< |  j j D]. } | j | j f | k r| j |  qqWxM | D]E \ }	 }
 y |  j |	 |
 f } Wn t k
 rYqX| j |  qW|  j j |  n  d  S)Nr   )r>   r   	get_modelLookupErrorr1   r8   r	   fieldsr&   remote_fieldr"   r   r%   r'   r2   lowerupdatebulk_updaterB   real_modelsr    r=   appendKeyErrorrender_multiple)r;   r    r!   Z	old_modelZrelated_modelsr@   Zdirect_related_modelsnamefieldr6   r7   Z	rel_modelZstates_to_be_renderedr#   r#   r$   r?   Y   sH    		 zProjectState.reload_modelc             C   sV   t  d d d   |  j j   D d |  j  } d |  j k rR |  j j   | _ n  | S)z*Returns an exact copy of this ProjectStater	   c             S   s%   i  |  ] \ } } | j    |  q Sr#   )clone)r(   kvr#   r#   r$   
<dictcomp>   s   	 z&ProjectState.clone.<locals>.<dictcomp>r:   r   )r9   r	   itemsr:   r>   r   rR   )r;   Z	new_stater#   r#   r$   rR      s    zProjectState.clonec             C   s   t  |  j |  j  S)N)	StateAppsr:   r	   )r;   r#   r#   r$   r      s    zProjectState.appsc             C   s%   t  |  j |  j d d |  _ |  j S)Nignore_swappableT)rW   r:   r	   r   )r;   r#   r#   r$   concrete_apps   s    zProjectState.concrete_appsc             C   sR   i  } x? | j  d d  D]+ } t j |  } | | | j | j f <q W|  |  S)z7Takes in an Apps and returns a ProjectState matching itZinclude_swappedT)
get_models
ModelState
from_modelr    r=   )clsr   Z
app_modelsr"   r@   r#   r#   r$   	from_apps   s
    zProjectState.from_appsc                sv   t  |  j j    t    j j    k r. d St  |  j  t    j  k rP d St   f d d   |  j j   D  S)NFc             3   s(   |  ] \ } } |   j  | k Vq d  S)N)r	   )r(   keyr"   )otherr#   r$   	<genexpr>   s    z&ProjectState.__eq__.<locals>.<genexpr>)r1   r	   keysr:   allrV   )r;   r`   r#   )r`   r$   __eq__   s
    *zProjectState.__eq__c             C   s   |  | k S)Nr#   )r;   r`   r#   r#   r$   __ne__   s    zProjectState.__ne__)__name__
__module____qualname____doc__r<   rA   rD   r?   rR   r   r   propertyrY   classmethodr^   rd   re   r#   r#   r#   r$   r9   ?   s   =
	r9   c                   s:   e  Z d  Z d Z d Z   f d d   Z d d   Z   S)AppConfigStubzP
    Stubs a Django AppConfig. Only provides a label, and a dict of models.
    r   c                s&   | |  _  t t |   j | d   d  S)N)labelsuperrl   r<   )r;   rm   )	__class__r#   r$   r<      s    	zAppConfigStub.__init__c             C   s   | |  _  d  S)N)r	   )r;   
all_modelsr#   r#   r$   import_models   s    zAppConfigStub.import_models)rf   rg   rh   ri   pathr<   rq   r#   r#   )ro   r$   rl      s   rl   c                   sy   e  Z d  Z d Z d   f d d  Z d d   Z e d d    Z d	 d
   Z d d   Z	 d d   Z
 d d   Z   S)rW   zo
    Subclass of the global Apps registry class to better handle dynamic model
    additions and removals.
    Fc       
         s!  g  |  _  xS | D]K } t j |  } x3 | j   D]% } |  j  j t j | d d  q2 Wq Wd d   | j   D } d d   t | t	 |   D } t
 t |   j |  |  j t	 | j    |  j   t |  j  }	 | r |	 t t j  h 8}	 n  |	 rt |  j |	    n  d  S)Nexclude_relsTc             S   s   h  |  ] } | j   q Sr#   )r    )r(   r@   r#   r#   r$   	<setcomp>   s   	 z%StateApps.__init__.<locals>.<setcomp>c             S   s   g  |  ] } t  |   q Sr#   )rl   )r(   rm   r#   r#   r$   r*      s   	 z&StateApps.__init__.<locals>.<listcomp>)rL   global_appsZget_app_configrZ   rM   r[   r\   valuessortedlistrn   rW   r<   rO   r1   _pending_operationsr   r   ZAUTH_USER_MODEL
ValueError_pending_models_error)
r;   r:   r	   rX   r    Zappr"   Z
app_labelsapp_configspending_models)ro   r#   r$   r<      s    	'# zStateApps.__init__c                s   d d       f d d    |  j  j  t   f d d   | D  } d d    d	 } d
 j | g  f d d   | D  S)af  
        Almost all internal uses of lazy operations are to resolve string model
        references in related fields. We can extract the fields from those
        operations and use them to provide a nicer error message.

        This will work for any function passed to lazy_related_operation() that
        has a keyword argument called 'field'.
        c             S   s   t  |  d d   S)NrQ   )getattr)Z	operationr#   r#   r$   extract_field   s    z6StateApps._pending_models_error.<locals>.extract_fieldc                s   d d   t    |   D S)Nc             s   s!   |  ] } | r t  |  Vq d  S)N)str)r(   rQ   r#   r#   r$   ra      s    zOStateApps._pending_models_error.<locals>.extract_field_names.<locals>.<genexpr>)map)
operations)r   r#   r$   extract_field_names   s    z<StateApps._pending_models_error.<locals>.extract_field_namesc             3   s-   |  ]# } | t     |    f Vq d  S)N)rw   )r(   	model_key)r   get_opsr#   r$   ra     s   z2StateApps._pending_models_error.<locals>.<genexpr>c             S   s1   d j  |  } | r d | n d } d |  | S)Nz, z (referred to by fields: %s)r   z%s.%s)join)r   rG   Z
field_listZ
field_textr#   r#   r$   
model_text  s    z3StateApps._pending_models_error.<locals>.model_textz(Unhandled pending operations for models:z
  c                s   g  |  ] }   |    q Sr#   r#   )r(   i)r   r#   r$   r*     s   	 z3StateApps._pending_models_error.<locals>.<listcomp>)ry   __getitem__rw   r   )r;   r}   Zmodels_fieldsmsgr#   )r   r   r   r   r$   r{      s    	zStateApps._pending_models_errorc             c   s6   |  j  } d |  _  z	 d  VWd  | |  _  |  j   Xd  S)NF)readyrC   )r;   r   r#   r#   r$   rK     s    				zStateApps.bulk_updatec             C   s   | s
 d  S|  j     | } x | r g  } xA | D]9 } y | j |   Wq3 t k
 rk | j |  Yq3 Xq3 Wt |  t |  k r t d | t   f   n  | } q  WWd  QXd  S)NzCannot resolve bases for %r
This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)
 in an app with no migrations; see https://docs.djangoproject.com/en/%s/topics/migrations/#dependencies for more)rK   renderr   rM   r   r   )r;   Zmodel_statesZunrendered_modelsZnew_unrendered_modelsr"   r#   r#   r$   rO     s     	zStateApps.render_multiplec             C   sI   t  g  i   } t j |  j  | _ t j |  j  | _ |  j | _ | S)zZ
        Return a clone of this registry, mainly used by the migration framework.
        )rW   copydeepcopyrp   r|   rL   )r;   rR   r#   r#   r$   rR   4  s
    zStateApps.clonec             C   s   | |  j  | | j j <| |  j k rO t |  |  j | <t   |  j | _ n  | |  j | j | j j <|  j |  |  j   d  S)N)	rp   r   r!   r|   rl   r   r	   Zdo_pending_operationsrC   )r;   r    r"   r#   r#   r$   register_model?  s    zStateApps.register_modelc             C   s<   y# |  j  | | =|  j | j | =Wn t k
 r7 Yn Xd  S)N)rp   r|   r	   rN   )r;   r    r!   r#   r#   r$   rB   H  s
    zStateApps.unregister_model)rf   rg   rh   ri   r<   r{   r   rK   rO   rR   r   rB   r#   r#   )ro   r$   rW      s   !	rW   c               @   s   e  Z d  Z d Z d d d d d  Z e d d    Z e d d d	   Z e 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)r[   a  
    Represents a Django Model. We don't use the actual Model class
    as it's not designed to have its options changed - instead, we
    mutate this one and then render it into a Model as required.

    Note that while you are allowed to mutate .fields, you are not allowed
    to mutate the Field instances inside there themselves - you must instead
    assign new ones, as these are not detached during a clone.
    Nc             C   s  | |  _  t |  |  _ | |  _ | p* i  |  _ | p? t j f |  _ | pN g  |  _ t	 |  j t
  ru t d   n  x | D] \ } } t | d  r t d |   n  | j r t | j d  r t d |   n  | j r| t | j j d  r| t d |   q| q| Wd  S)NzCModelState.fields cannot be a dict - it must be a list of 2-tuples.r"   z7ModelState.fields cannot be bound to a model - "%s" is.r   z_ModelState.fields cannot refer to a model class - "%s.to" does. Use a string reference instead.zdModelState.fields cannot refer to a model class - "%s.through" does. Use a string reference instead.)r    r   rP   rG   optionsr	   r,   basesmanagersr   dictrz   hasattrr&   r'   Zmany_to_manyrH   Zthrough)r;   r    rP   rG   r   r   r   rQ   r#   r#   r$   r<   [  s(    		zModelState.__init__c             C   s   |  j  j   S)N)rP   rI   )r;   r#   r#   r$   r=   w  s    zModelState.name_lowerFc                s  g  } x  j  j D] } t | d d  r7 | r7 q n  t | t  rL q n  t | j d d } y | j | | j   f  Wq t	 k
 r } z$ t	 d |  j  j
 | f   WYd d } ~ Xq Xq W| sbx  j  j D] } t | j d d } y | j | | j   f  Wq t	 k
 rZ} z$ t	 d |  j  j | f   WYd d } ~ Xq Xq Wn  i  } x t D] } | d k rqoqo|  j  j k ro| d	 k r j  j d	 } t t |   | | <q| d
 k r j  j d
 }	 t t |	   | | <q j  j | | | <qoqoW|  j |  } | rfx0 d	 d
 d g D] }
 |
 | k rC| |
 =qCqCWn    f d d     t t      d  f d d   } t d d   | D  } t d d   | D  st j f } n  i    f d d   } t  d  rt  j j  }  j j r8|  j  n d t j   f  | <xL t  j  j  D]8 \ } } } | j d k sa| j rqan  | |  qaWd d   t  j   d d d   D } | d t j   f g k rg  } qn g  } |   j  j  j  j | | | |  S)zH
        Feed me a model, get a ModelState representing it out.
        rH   NZstrings_onlyTz'Couldn't reconstruct field %s on %s: %sz+Couldn't reconstruct m2m field %s on %s: %sr   r    Zunique_togetherZindex_togetherZorder_with_respect_toc                s\   g  } xO |  j  D]D } t | d  rG | j j rG | j   |   q | j |  q W| S)Nr   )	__bases__r   r   Zabstractr3   rM   )r"   r   base)flatten_basesr#   r$   r     s    z,ModelState.from_model.<locals>.flatten_basesr_   c                s     j  j |   S)N)__mro__index)x)r"   r#   r$   <lambda>  s    z'ModelState.from_model.<locals>.<lambda>c             s   s0   |  ]& } t  | d   r$ | j j n | Vq d S)r   N)r   r   Zlabel_lower)r(   r   r#   r#   r$   ra     s   z(ModelState.from_model.<locals>.<genexpr>c             s   s3   |  ]) } t  | t j  p* t | t j  Vq d  S)N)r   r   r   r+   r	   r,   )r(   r   r#   r#   r$   ra     s    c       
         s}   |  j    \ } } } } } | r< t |  } | j   } n t |  } | | |   } t |  j  }	 |  j | f   |	 <d  S)N)deconstructr   
as_managerr   rP   creation_counter)
Zmgrr   manager_pathqs_pathargskwargsqs_classinstancemanager_classrP   )managers_mappingr#   r$   reconstruct_manager  s    z2ModelState.from_model.<locals>.reconstruct_manager_default_managerr   Z_base_managerc             S   s(   g  |  ] \ } \ } } | | f  q Sr#   r#   )r(   rP   ccr   r#   r#   r$   r*     s   	 z)ModelState.from_model.<locals>.<listcomp>c             S   s   |  d S)Nr   r#   )rT   r#   r#   r$   r     s    Zobjects)zappsz	app_label)r   Zlocal_fieldsr~   r   r
   r   rP   rM   rR   	TypeErrorrm   Zlocal_many_to_manyZobject_namer   Zoriginal_attrsr1   r   force_text_recursiverw   r   anyr	   r,   r   r   Zuse_in_migrationsManagerr   rV   r    )r]   r"   rs   rG   rQ   rP   er   utitr_   Zflattened_basesr   r   Zdefault_manager_name_managerr   r#   )r   r   r"   r$   r\   {  s    	$	'*	"	"		zModelState.from_modelc                s   t  | t j  r t |  St  | t  rB   f d d   | D St  | t  rn t   f d d   | D  St  | t  r t   f d d   | D  St  | t  r   f d d   | j   D S| S)Nc                s   g  |  ] }   j  |   q Sr#   )r   )r(   r   )r]   r#   r$   r*   
  s   	 z3ModelState.force_text_recursive.<locals>.<listcomp>c             3   s   |  ] }   j  |  Vq d  S)N)r   )r(   r   )r]   r#   r$   ra     s    z2ModelState.force_text_recursive.<locals>.<genexpr>c             3   s   |  ] }   j  |  Vq d  S)N)r   )r(   r   )r]   r#   r$   ra     s    c                s1   i  |  ]' \ } }   j  |    j  |   q Sr#   )r   )r(   rS   rT   )r]   r#   r$   rU     s   	z3ModelState.force_text_recursive.<locals>.<dictcomp>)	r   r   r   r   rx   r   r1   r   rV   )r]   valuer#   )r]   r$   r     s    
zModelState.force_text_recursivec             c   s   t  |  j d d d   } x | D]y \ } } t |  } | j   \ } } } } } | r{ t |  }	 | |	 j   f Vq" t |  }
 | |
 | |   f Vq" Wd S)z,Deep-clone the managers using deconstructionr_   c             S   s   |  d j  S)Nr   )r   )rT   r#   r#   r$   r     s    z/ModelState.construct_managers.<locals>.<lambda>N)rw   r   r   r   r   r   )r;   Zsorted_managersZmgr_namer   r   r   r   r   r   r   r   r#   r#   r$   construct_managers  s    zModelState.construct_managersc             C   sR   |  j  d |  j d |  j d t |  j  d t |  j  d |  j d t |  j   S)z(Returns an exact copy of this ModelStater    rP   rG   r   r   r   )	ro   r    rP   rx   rG   r   r   r   r   )r;   r#   r#   r$   rR   $  s    				zModelState.clonec                s   i |  j  d 6  d 6} | j |  j  t t d  t   |  } y& t   f d d   |  j D  } Wn( t k
 r t d |  j f   Yn Xd d   |  j	 D } | | d <d	 | d
 <| j |  j
    t t |  j  | |  S)zACreates a Model object from our current state into the given appsr    r   ZMetac             3   s6   |  ], } t  | t j  r*   j |  n | Vq d  S)N)r   r   r   rE   )r(   r   )r   r#   r$   ra   8  s   z$ModelState.render.<locals>.<genexpr>z(Cannot resolve one or more bases from %rc             S   s%   i  |  ] \ } } | j    |  q Sr#   )rR   )r(   rP   rQ   r#   r#   r$   rU   >  s   	 z%ModelState.render.<locals>.<dictcomp>Z__fake__rg   )r    rJ   r   typer   r   r   rF   r   rG   r   rP   )r;   r   Zmeta_contentsmetar   bodyr#   )r   r$   r   /  s"    

zModelState.renderc             C   sG   x' |  j  D] \ } } | | k r
 | Sq
 Wt d | |  j f   d  S)NzNo field called %s on model %s)rG   rz   rP   )r;   rP   fnamerQ   r#   r#   r$   get_field_by_nameL  s    zModelState.get_field_by_namec             C   s   d |  j  |  j f S)Nz<ModelState: '%s.%s'>)r    rP   )r;   r#   r#   r$   __repr__R  s    zModelState.__repr__c             C   s   |  j  | j  k o |  j | j k o t |  j  t | j  k o t d d   t |  j | j  D  o |  j | j k o |  j | j k o |  j | j k S)Nc             s   sY   |  ]O \ \ } } \ } } | | k oP | j    d  d  | j    d  d  k Vq d S)r   N)r   )r(   Zk1f1Zk2f2r#   r#   r$   ra   Z  s   z$ModelState.__eq__.<locals>.<genexpr>)	r    rP   r   rG   rc   zipr   r   r   )r;   r`   r#   r#   r$   rd   U  s    zModelState.__eq__c             C   s   |  | k S)Nr#   )r;   r`   r#   r#   r$   re   a  s    zModelState.__ne__)rf   rg   rh   ri   r<   r   r=   rk   r\   r   r   rR   r   r   r   rd   re   r#   r#   r#   r$   r[   P  s   	r[   ).
__future__r   r   collectionsr   
contextlibr   Zdjango.appsr   Zdjango.apps.registryr   r   ru   Zdjango.confr   Z	django.dbr	   Zdjango.db.models.fields.proxyr
   Zdjango.db.models.fields.relatedr   Zdjango.db.models.optionsr   r   Zdjango.db.models.utilsr   Zdjango.utilsr   Zdjango.utils.encodingr   r   Zdjango.utils.functionalr   Zdjango.utils.module_loadingr   Zdjango.utils.versionr   
exceptionsr   r%   r8   objectr9   rl   rW   r[   r#   r#   r#   r$   <module>   s.   ~