Override _clone to preserve additional information needed by
        MultilingualModelQuerySet.
11858
def _clone(self, klass=None, **kwargs):
        
        clone = super(MultilingualModelQuerySet, self)._clone(klass, **kwargs)
        clone._default_language = getattr(self, '_default_language', None)
        return clone
221240
def translate(self, dialect):
        """"""
        new_resultset = copy(self)
        new_resultset.dialect = dialect

        for result in new_resultset:
            for dimensionvalue in result.dimensionvalues:
                dimensionvalue.value = dimensionvalue.translate(dialect)
        return new_resultset
792856
def _clone_reverses(self, old_reverses):
        

        for ctype, reverses in old_reverses.items():
            for parts in reverses.values():
                sub_objs = parts[1]
                field_name = parts[0]

                attrs = {}
                for sub_obj in sub_objs:
                    if ctype != 'm2m' and not attrs:
                        field = sub_obj._meta.get_field(field_name)
                        attrs = {
                            field.column: getattr(self, field.rel.field_name)
                        }
                    sub_obj._clone(**attrs)

                if ctype == 'm2m':
                    setattr(self, field_name, sub_objs)
571043
def _get_any_translated_model(self, meta=None):
        
        if meta is None:
            meta = self._parler_meta.root

        tr_model = meta.model
        local_cache = self._translations_cache[tr_model]
        if local_cache:
            # There is already a language available in the case. No need for queries.
            # Give consistent answers if they exist.
            check_languages = [self._current_language] + self.get_fallback_languages()
            try:
                for fallback_lang in check_languages:
                    trans = local_cache.get(fallback_lang, None)
                    if trans and not is_missing(trans):
                        return trans
                return next(t for t in six.itervalues(local_cache) if not is_missing(t))
            except StopIteration:
                pass

        try:
            # Use prefetch if available, otherwise perform separate query.
            prefetch = self._get_prefetched_translations(meta=meta)
            if prefetch is not None:
                translation = prefetch[0]  # Already a list
            else:
                translation = self._get_translated_queryset(meta=meta)[0]
        except IndexError:
            return None
        else:
            local_cache[translation.language_code] = translation
            _cache_translation(translation)
            return translation
1284952
protected function updateAttributesWithTranslated()
    {
        $translationInfo = $this->translationAnalyzer()->analyze($this->model());

        $attributes = $this->info['attributes'];

        // Mark the fillable fields on the translation model
        foreach ($translationInfo['attributes'] as $key => $attribute) {

            /** @var ModelAttributeData $attribute */
            if ( ! $attribute->translated) {
                continue;
            }

            if ( ! isset($attributes[$key])) {
                $attributes[$key] = $attribute;
            }

            /** @var ModelAttributeData $attributeData */
            $attributeData = $attributes[$key];
            $attributeData->merge($attribute);

            $attributes[$key] = $attributeData;
        }

        $this->info['attributes'] = $attributes;
    }
796383
def _get_translated_model(self, language_code=None, use_fallback=False, auto_create=False, meta=None):
        
        if self._parler_meta is None:
            raise ImproperlyConfigured("No translation is assigned to the current model!")
        if self._translations_cache is None:
            raise RuntimeError("Accessing translated fields before super.__init__() is not possible.")

        if not language_code:
            language_code = self._current_language
            if language_code is None:
                raise ValueError(get_null_language_error())

        if meta is None:
            meta = self._parler_meta.root  # work on base model by default

        local_cache = self._translations_cache[meta.model]

        # 1. fetch the object from the local cache
        try:
            object = local_cache[language_code]

            # If cached object indicates the language doesn't exist, need to query the fallback.
            if not is_missing(object):
                return object
        except KeyError:
            # 2. No cache, need to query
            # Check that this object already exists, would be pointless otherwise to check for a translation.
            if not self._state.adding and self.pk is not None:
                prefetch = self._get_prefetched_translations(meta=meta)
                if prefetch is not None:
                    # 2.1, use prefetched data
                    # If the object is not found in the prefetched data (which contains all translations),
                    # it's pointless to check for memcached (2.2) or perform a single query (2.3)
                    for object in prefetch:
                        if object.language_code == language_code:
                            local_cache[language_code] = object
                            _cache_translation(object)  # Store in memcached
                            return object
                else:
                    # 2.2, fetch from memcached
                    object = get_cached_translation(self, language_code, related_name=meta.rel_name, use_fallback=use_fallback)
                    if object is not None:
                        # Track in local cache
                        if object.language_code != language_code:
                            local_cache[language_code] = MISSING  # Set fallback marker
                        local_cache[object.language_code] = object
                        return object
                    elif is_missing(local_cache.get(language_code, None)):
                        # If get_cached_translation() explicitly set the "does not exist" marker,
                        # there is no need to try a database query.
                        pass
                    else:
                        # 2.3, fetch from database
                        try:
                            object = self._get_translated_queryset(meta).get(language_code=language_code)
                        except meta.model.DoesNotExist:
                            pass
                        else:
                            local_cache[language_code] = object
                            _cache_translation(object)  # Store in memcached
                            return object

        # Not in cache, or default.
        # Not fetched from DB

        # 3. Auto create?
        if auto_create:
            # Auto create policy first (e.g. a __set__ call)
            kwargs = {
                'language_code': language_code,
            }
            if self.pk:
                # ID might be None at this point, and Django does not allow that.
                kwargs['master'] = self

            object = meta.model(**kwargs)
            local_cache[language_code] = object
            # Not stored in memcached here yet, first fill + save it.
            return object

        # 4. Fallback?
        fallback_msg = None
        lang_dict = get_language_settings(language_code)

        if language_code not in local_cache:
            # Explicitly set a marker for the fact that this translation uses the fallback instead.
            # Avoid making that query again.
            local_cache[language_code] = MISSING  # None value is the marker.
            if not self._state.adding or self.pk is not None:
                _cache_translation_needs_fallback(self, language_code, related_name=meta.rel_name)

        fallback_choices = [lang_dict['code']] + list(lang_dict['fallbacks'])
        if use_fallback and fallback_choices:
            # Jump to fallback language, return directly.
            # Don't cache under this language_code
            for fallback_lang in fallback_choices:
                if fallback_lang == language_code:  # Skip the current language, could also be fallback 1 of 2 choices
                    continue

                try:
                    return self._get_translated_model(fallback_lang, use_fallback=False, auto_create=auto_create, meta=meta)
                except meta.model.DoesNotExist:
                    pass

            fallback_msg = " (tried fallbacks {0})".format(', '.join(lang_dict['fallbacks']))

        # None of the above, bail out!
        raise meta.model.DoesNotExist(
            "{0} does not have a translation for the current language!\n"
            "{0} ID #{1}, language={2}{3}".format(self._meta.verbose_name, self.pk, language_code, fallback_msg or ''
        ))
299819
def cloneQuery(self, limit=_noItem, sort=_noItem):
        
        newq = self.query.cloneQuery(limit=limit, sort=sort)
        return self.__class__(newq)
958097
def post_translation(self, query, bug):
        
        ignore = query

        # RHBZ _still_ returns component and version as lists, which
        # deviates from upstream. Copy the list values to components
        # and versions respectively.
        if 'component' in bug and "components" not in bug:
            val = bug['component']
            bug['components'] = isinstance(val, list) and val or [val]
            bug['component'] = bug['components'][0]

        if 'version' in bug and "versions" not in bug:
            val = bug['version']
            bug['versions'] = isinstance(val, list) and val or [val]
            bug['version'] = bug['versions'][0]

        # sub_components isn't too friendly of a format, add a simpler
        # sub_component value
        if 'sub_components' in bug and 'sub_component' not in bug:
            val = bug['sub_components']
            bug['sub_component'] = ""
            if isinstance(val, dict):
                values = []
                for vallist in val.values():
                    values += vallist
                bug['sub_component'] = " ".join(values)
1066817
def _clone(self, **attrs):
        

        with xact():
            # Gather objs we'll need save after
            old_m2ms = self._gather_m2ms()
            old_reverses = self._gather_reverses()

            for k, v in attrs.items():
                setattr(self, k, v)

            # Do the clone
            self.prep_for_clone()
            self.validate_unique()
            # Prevent last save from changing
            self.save(last_save=self.last_save)

            # save m2ms
            self._set_m2ms(old_m2ms)
            # Prevent last save from changing
            self.save(last_save=self.last_save)

            # save reverses
            self._clone_reverses(old_reverses)
1085604
def _set_translated_fields(self, language_code=None, **fields):
        
        objects = []  # no generator, make sure objects are all filled first
        for parler_meta, model_fields in self._parler_meta._split_fields(**fields):
            translation = self._get_translated_model(language_code=language_code, auto_create=True, meta=parler_meta)
            for field, value in six.iteritems(model_fields):
                setattr(translation, field, value)

            objects.append(translation)
        return objects
1015019
function(encoded, key, model, overwrite)
  {
    if ( !isObject( encoded ) )
    {
      return model;
    }

    var db = this;
    var key = key || db.keyHandler.getKey( encoded, true );

    // The remote source might be crazy, if the key isn't there then log it and ignore it
    if ( !isValue( key ) )
    {
      Rekord.debug( Rekord.Debugs.MISSING_KEY, db, encoded );

      return;
    }

    var model = model || db.all[ key ];
    var decoded = db.decode( copy( encoded ) );

    // Reject the data if it's a lower revision
    if ( model )
    {
      var revisionRejected = this.revisionFunction( model, encoded );

      if ( revisionRejected )
      {
        Rekord.debug( Rekord.Debugs.SAVE_OLD_REVISION, db, model, encoded );

        return model;
      }
    }

    // If the model already exists, update it.
    if ( model )
    {
      if ( db.keyHandler.hasKeyChange( model, decoded ) )
      {
        key = model.$setKey( db.keyHandler.getKey( decoded, true ) );
      }

      db.addReference( model, key );

      if ( !model.$saved )
      {
        model.$saved = {};
      }

      var current = model; // model.$toJSON( true );
      var conflicts = {};
      var conflicted = false;
      var updated = {};
      var previous = {};
      var saved = {};
      var notReallySaved = isEmpty( model.$saved );
      var relations = db.relations;
      var compareTo = db.decode( model.$saved ); // model.$saved

      for (var prop in encoded)
      {
        if ( prop.charAt(0) === '$' )
        {
          continue;
        }

        if ( prop in relations )
        {
          model.$set( prop, encoded[ prop ], true );

          continue;
        }

        var currentValue = current[ prop ];
        var savedValue = compareTo[ prop ];

        previous[ prop ] = model[ prop ];
        saved[ prop ] = savedValue;

        if ( notReallySaved || overwrite || equals( currentValue, savedValue ) )
        {
          model[ prop ] = decoded[ prop ];
          updated[ prop ] = encoded[ prop ];

          if ( model.$local )
          {
            model.$local[ prop ] = encoded[ prop ];
          }
        }
        else
        {
          conflicts[ prop ] = encoded[ prop ];
          conflicted = true;
        }

        model.$saved[ prop ] = copy( encoded[ prop ] );
      }

      if ( conflicted )
      {
        model.$trigger( Model.Events.PartialUpdate, [encoded, updated, previous, saved, conflicts] );
      }
      else
      {
        model.$trigger( Model.Events.FullUpdate, [encoded, updated, previous, saved, conflicts] );
      }

      model.$trigger( Model.Events.RemoteUpdate, [encoded, updated, previous, saved, conflicts] );

      model.$addOperation( SaveNow );

      if ( !db.models.has( key ) )
      {
        db.saveReference( model, key );
        db.trigger( Database.Events.ModelAdded, [model, true] );
      }
    }
    // The model doesn't exist, create it.
    else
    {
      model = db.createModel( decoded, true );

      if ( model )
      {
        if ( db.cache === Cache.All )
        {
          model.$local = model.$toJSON( false );
          model.$local.$status = model.$status;
          model.$saved = model.$local.$saved = model.$toJSON( true );

          model.$addOperation( SaveNow );
        }
        else
        {
          model.$saved = model.$toJSON( true );
        }
      }
    }

    return model;
  }
163184
private function populateTranslations()
    {
        //translations
        $aRelated = $this->owner->getRelatedRecords();
        if (isset($aRelated[$this->relation]) && $aRelated[$this->relation] != null) {
            if (is_array($aRelated[$this->relation])) {
                foreach ($aRelated[$this->relation] as $model) {
                    $this->_models[$model->getAttribute($this->languageField)] = $model;
                }
            } else {
                $model = $aRelated[$this->relation];
                $this->_models[$model->getAttribute($this->languageField)] = $model;
            }
        }
    }
586814
def include(self, *fields, **kwargs):
        
        clone = self._clone()

        # Preserve the stickiness of related querysets
        # NOTE: by default _clone will clear this attribute
        # .include does not modify the actual query, so we
        # should not clear `filter_is_sticky`
        if self.query.filter_is_sticky:
            clone.query.filter_is_sticky = True

        clone._include_limit = kwargs.pop('limit_includes', None)
        assert not kwargs, '"limit_includes" is the only accepted kwargs. Eat your heart out 2.7'

        # Copy the behavior of .select_related(None)
        if fields == (None, ):
            for field in clone._includes.keys():
                clone.query._annotations.pop('__{}'.format(field.name), None)
            clone._includes.clear()
            return clone

        # Parse everything the way django handles joins/select related
        # Including multiple child fields ie .include(field1__field2, field1__field3)
        # turns into {field1: {field2: {}, field3: {}}
        for name in fields:
            ctx, model = clone._includes, clone.model
            for spl in name.split('__'):
                field = model._meta.get_field(spl)
                if isinstance(field, ForeignObjectRel) and field.is_hidden():
                    raise ValueError('Hidden field "{!r}" has no descriptor and therefore cannot be included'.format(field))
                model = field.related_model
                ctx = ctx.setdefault(field, OrderedDict())

        for field in clone._includes.keys():
            clone._include(field)

        return clone
364974
def pre_sql_setup(self):
        
        super(MultilingualSQLCompiler, self).pre_sql_setup()

        if not self.query.include_translation_data:
            return

        opts = self.query.model._meta
        qn = self.quote_name_unless_alias
        qn2 = self.connection.ops.quote_name

        if hasattr(opts, 'translation_model'):
            master_table_name = self.query.join((None, opts.db_table, None, None))
            translation_opts = opts.translation_model._meta
            trans_table_name = translation_opts.db_table
            for language_code in get_language_code_list():
                table_alias = get_translation_table_alias(trans_table_name,
                                                          language_code)
                trans_join = ("LEFT JOIN %s AS %s ON ((%s.master_id = %s.%s) AND (%s.language_code = '%s'))"
                           % (qn2(translation_opts.db_table),
                           qn2(table_alias),
                           qn2(table_alias),
                           qn(master_table_name),
                           qn2(opts.pk.column),
                           qn2(table_alias),
                           language_code))
                self.query.extra_join[table_alias] = trans_join
571987
private void cacheUniqueSelectRef(Object object, MappedStatement mt, String cacheKey) {
		Collection<QueryMethodCache> mcs = queryCacheMethods.get(mt.getId().substring(0, mt.getId().lastIndexOf(SPLIT_PONIT))).values();
		outter:for (QueryMethodCache methodCache : mcs) {
			if(methodCache.isPk || methodCache.groupRalated)continue;
			try {	
				Object[] cacheFieldValues = new Object[methodCache.fieldNames.length];
				for (int i = 0; i < cacheFieldValues.length; i++) {
					if(methodCache.fieldNames[i] == null)break outter;
					cacheFieldValues[i] = ReflectUtils.getObjectValue(object, methodCache.fieldNames[i]);
					if(cacheFieldValues[i] == null)continue outter;
				}
				String fieldCacheKey = genarateQueryCacheKey(methodCache.keyPattern , cacheFieldValues);
				
				cacheFieldRefKey(fieldCacheKey,cacheKey, methodCache.getExpire());
				if(logger.isDebugEnabled())logger.debug("_autocache_ method[{}] add ref cacheKey:{}",mt.getId(),fieldCacheKey);
			} catch (Exception e) {
				logger.warn("cacheUniqueSelectRef:"+cacheKey,e);
			}
		}
	}
883089
def _canonicalize_query(self, query):

        

        def transform_query(q):

            for encoder in self.query_encoders:
                q = encoder.encode(q,[])

            if isinstance(q, dict):
                nq = {}
                for key,value in q.items():
                    new_key = key
                    if isinstance(value,dict) and len(value) == 1 and list(value.keys())[0].startswith('$'):
                        if list(value.keys())[0] in ('$all','$in'):
                            if list(value.values())[0] and isinstance(list(value.values())[0][0],Document):
                                if self._use_pk_based_refs:
                                    new_key+='.pk'
                                else:
                                    new_key+='.__ref__'
                    elif isinstance(value,Document):
                        if self._use_pk_based_refs:
                            new_key+='.pk'
                        else:
                            new_key+='.__ref__'
                    nq[new_key] = transform_query(value)
                return nq
            elif isinstance(q, (list,QuerySet,tuple)):
                return [transform_query(x) for x in q]
            elif isinstance(q,Document):
                collection = self.get_collection_for_obj(q)
                if self._use_pk_based_refs:
                    return q.pk
                else:
                    return "%s:%s" % (collection,q.pk)
            else:
                return q

        return transform_query(query)
272611
def transform_model(cls) -> None:
    
    if cls.name != "Model":
        appname = "models"
        for mcls in cls.get_children():
            if isinstance(mcls, ClassDef):
                for attr in mcls.get_children():
                    if isinstance(attr, Assign):
                        if attr.targets[0].name == "app":
                            appname = attr.value.value

        mname = "{}.{}".format(appname, cls.name)
        MODELS[mname] = cls

        for relname, relval in FUTURE_RELATIONS.get(mname, []):
            cls.locals[relname] = relval

        for attr in cls.get_children():
            if isinstance(attr, Assign):
                try:
                    attrname = attr.value.func.attrname
                except AttributeError:
                    pass
                else:
                    if attrname in ["ForeignKeyField", "ManyToManyField"]:
                        tomodel = attr.value.args[0].value
                        relname = ""
                        if attr.value.keywords:
                            for keyword in attr.value.keywords:
                                if keyword.arg == "related_name":
                                    relname = keyword.value.value

                        if not relname:
                            relname = cls.name.lower() + "s"

                        # Injected model attributes need to also have the relation manager
                        if attrname == "ManyToManyField":
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "ManyToManyRelationManager"
                                )[1][0],
                            ]
                        else:
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "RelationQueryContainer"
                                )[1][0],
                            ]

                        if tomodel in MODELS:
                            MODELS[tomodel].locals[relname] = relval
                        else:
                            FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval))

    cls.locals["_meta"] = [
        MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class()
    ]
    if "id" not in cls.locals:
        cls.locals["id"] = [nodes.ClassDef("id", None)]