<s> import warnings <EOL> from collections import deque <EOL> from django . db . models . query import QuerySet <EOL> def _clone_queryset ( qs , klass ) : <EOL> cloned_qs = klass ( <EOL> model = qs . model , <EOL> query = qs . query . clone ( ) , <EOL> using = qs . _db , <EOL> hints = qs . _hints , <EOL> ) <EOL> cloned_qs . _for_write = qs . _for_write <EOL> cloned_qs . _prefetch_related_lookups = qs . _prefetch_related_lookups [ : ] <EOL> cloned_qs . _known_related_objects = qs . _known_related_objects <EOL> return cloned_qs <EOL> def ensure_instances_consistent ( queryset , instance_pks ) : <EOL> """<STR_LIT>""" <EOL> class EnsuredQuerySet ( queryset . __class__ ) : <EOL> def _fetch_all ( self ) : <EOL> super ( EnsuredQuerySet , self ) . _fetch_all ( ) <EOL> new_qs = _clone_queryset ( qs = self , klass = queryset . __class__ ) <EOL> new_qs . query . high_mark = None <EOL> new_qs . query . low_mark = <NUM_LIT:0> <EOL> consistently_got = list ( new_qs . filter ( pk__in = instance_pks ) ) <EOL> def is_less ( lhs , rhs ) : <EOL> for field in queryset . query . order_by : <EOL> negative = field . startswith ( "<STR_LIT:->" ) <EOL> if negative : <EOL> field = field [ <NUM_LIT:1> : ] <EOL> if getattr ( lhs , field , None ) < getattr ( rhs , field , None ) : <EOL> return False <EOL> else : <EOL> if getattr ( lhs , field , None ) >= getattr ( rhs , field , None ) : <EOL> return False <EOL> else : <EOL> return True <EOL> new_result_cache = [ ] <EOL> count = self . query . high_mark <EOL> consistently_got = deque ( sorted ( consistently_got , cmp = is_less ) ) <EOL> for item in self . _result_cache : <EOL> try : <EOL> consistent_item = consistently_got [ <NUM_LIT:0> ] <EOL> if item == consistent_item or is_less ( consistent_item , item ) : <EOL> new_result_cache . append ( consistent_item ) <EOL> consistently_got . popleft ( ) <EOL> if item == consistent_item : <EOL> continue <EOL> except IndexError : <EOL> pass <EOL> if item . pk in instance_pks : <EOL> continue <EOL> new_result_cache . append ( item ) <EOL> else : <EOL> if consistently_got : <EOL> new_result_cache . extend ( list ( consistently_got ) ) <EOL> self . _result_cache = new_result_cache [ : count ] <EOL> if isinstance ( queryset , QuerySet ) : <EOL> return _clone_queryset ( qs = queryset , klass = EnsuredQuerySet ) <EOL> else : <EOL> return queryset <EOL> def ensure_instance_consistent ( queryset , instance_id ) : <EOL> return ensure_instances_consistent ( queryset , [ instance_id ] ) <EOL> def ensure_instance_included ( queryset , instance_id ) : <EOL> warnings . warn ( "<STR_LIT>" , DeprecationWarning ) <EOL> return ensure_instance_consistent ( queryset , instance_id ) </s>
