def get_field_by_name(self, name): if name is 'pk': name = 'id' try: if hasattr(self, '_name_map') and name in self._name_map: return self._name_map[name] else: cache = self.init_name_map() return cache[name] except KeyError: raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def get_value(self, model, field_name, query): field_to_index = self.get_field_to_index(model, field_name) if field_to_index in query.fields: values = [] for obj in query.objs: value = field_to_index.value_from_object(obj) values.append(value) if len(values): return values raise FieldDoesNotExist('Cannot find field in query.')
def get_field(self, name, many_to_many=True): """ Returns the requested field by name. Raises FieldDoesNotExist on error. """ to_search = (self.fields + self.many_to_many) if many_to_many else self.fields for f in to_search: if f.name == name: return f raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def create_compound_indexes(indexes, **kwargs): if not indexes: return indexes = [(index if isinstance(index, tuple) else (index, ASCENDING)) for index in indexes] invalid = first(lambda (name, direction): name not in field_names, indexes) if invalid is not None: from django.db.models.fields import FieldDoesNotExist raise FieldDoesNotExist("%r has no field named %r" % (meta.object_name, invalid)) collection.ensure_index(indexes, **kwargs)
def get_virtual_field(model, field_name): matched_fields = filter( lambda f: f.name == field_name, model._meta.virtual_fields, ) if len(matched_fields) == 1: return matched_fields[0] raise FieldDoesNotExist("{!r} has no virtual field named {!r}".format( model, field_name, ))
def resolve_field(name, app_label=None): """Returns the field descriptor specified by the string `name` which should be either `model.field` or `app_label.model.field`. """ l = name.split('.') if len(l) == 3: app_label = l[0] del l[0] if len(l) == 2: model = apps.get_model(app_label, l[0]) if model is None: raise FieldDoesNotExist("No model named '%s.%s'" % (app_label, l[0])) return model._meta.get_field(l[1]) # fld, remote_model, direct, m2m = model._meta.get_field_by_name(l[1]) # assert remote_model is None or issubclass(model, remote_model), \ # "resolve_field(%r) : remote model is %r (expected None or base of %r)" % ( # name, remote_model, model) # return fld raise FieldDoesNotExist(name)
def get_field(self, name): if (not self.is_django_model or MIN_SUPPORTED_VERSION <= _VERSION <= (1, 7)): return self.opts.get_field(name) else: field = self.opts.get_field(name) if (field.auto_created or field.is_relation and field.related_model is None): raise FieldDoesNotExist("{} has no field named '{}'".format( self.model.__name__, name)) return field
def create_compound_indexes(indexes, **kwargs): # if (field1, field2) in the sparse_indexes list # then set sparse to true kwargs['sparse'] = tuple(indexes) in sparse_indexes if not indexes: return indexes = [(index if isinstance(index, tuple) else (index, ASCENDING)) for index in indexes] invalid = first(lambda (name, direction): name not in field_names, indexes) if invalid is not None: from django.db.models.fields import FieldDoesNotExist raise FieldDoesNotExist("%r has no field named %r" % (meta.object_name, invalid)) ensure_index(indexes, **kwargs)
def index_fields_group(self, model, group, **kwargs): """Create indexes for fields in group that belong to model. This method is used to do compound indexes. :param model: The model containing the fields inside group. :param group: A ``dict`` containing the fields map to index. :param \*\*kwargs: Extra kwargs not used in this engine. Example >>> class TestFieldModel(Task): ... ... class MongoMeta: ... index_together = [{ ... 'fields' : [ ('title', False), 'mlist'] ... }] ... """ if not isinstance(group, dict): raise TypeError("Indexes group has to be instance of dict") fields = group.pop("fields") if not isinstance(fields, (list, tuple)): raise TypeError("index_together fields has to be instance of list") opts = model._meta col = getattr(self.connection.db_connection, opts.db_table) checked_fields = [] model_fields = [f.name for f in opts.local_fields] for field in fields: field_name = field direction = 1 if isinstance(field, (tuple, list)): field_name = field[0] direction = (field[1] and 1) or -1 if not field_name in model_fields: from django.db.models.fields import FieldDoesNotExist raise FieldDoesNotExist('%s has no field named %r' % (opts.object_name, field_name)) checked_fields.append((field_name, direction)) col.ensure_index(checked_fields, **group)
def get_field_by_name(self, name): """ Returns the (field_object, model, direct, m2m), where field_object is the Field instance for the given name, model is the model containing this field (None for local fields), direct is True if the field exists on this model, and m2m is True for many-to-many relations. When 'direct' is False, 'field_object' is the corresponding RelatedObject for this field (since the field doesn't have an instance associated with it). """ if name in self.document._fields: field = self.document._fields[name] if isinstance(field, ReferenceField): return (field, field.document_type, False, False) else: return (field, None, True, False) else: raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def update_or_create_customized_fields( self, model, customized_fields_data, widget="text" ): for field_data in customized_fields_data: field_data["item"] = self try: # Get the old value and update/create the field if 'id' in field_data: qs = model.objects.filter(pk=field_data['id']) if not qs: pass existing_field = qs[0] old_value = existing_field.value qs.update(**field_data) else: old_value = None model.objects.create( **field_data ) # Extract the new_value if "unit" in field_data: new_value = "%s %s" % ( field_data['value'], field_data['unit'] ) else: new_value = field_data['value'] if old_value != new_value: ItemEditRecord.objects.create( field=field_data['title'], original_value=old_value, new_value=new_value, item=self, widget=widget, ) except FieldDoesNotExist, e: print("\n\t item.update_customized_char_fields():") print("""\t\titem.update_customized_char_fields error: field_data contains stuffs that are not in the model definition!!!! """) print("error message = %s" % (e.message)) raise FieldDoesNotExist("\n\te.message = %s" % (e.message))
def get_field_by_name(self, name): """ Returns the (field_object, model, direct, m2m), where field_object is the Field instance for the given name, model is the model containing this field (None for local fields), direct is True if the field exists on this model, and m2m is True for many-to-many relations. When 'direct' is False, 'field_object' is the corresponding RelatedObject for this field (since the field doesn't have an instance associated with it). Uses a cache internally, so after the first access, this is very fast. """ try: try: return self._name_map[name] except AttributeError: cache = self.init_name_map() return cache[name] except KeyError: raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def __init__(self, *args, **kwargs): super(SubtreeImport, self).__init__(*args, **kwargs) #set key_in_self from related_model verbose_name if not set if not self.key_in_self: self.key_in_self = self.related_model._meta.verbose_name #check key_in_self (strip '_id' in check) if not self.key_in_self in self.model._meta.get_all_field_names(): raise FieldDoesNotExist(self.key_in_self) #set related_tsv_key from related_model verbose_name if not set if not self.related_tsv_key: self.related_tsv_key = 'sid_' + self.related_model._meta.verbose_name #determine many_to_many from field try: self.many_to_many = self.model._meta.get_field(self.key_in_self).__class__ == ManyToManyField except FieldDoesNotExist: # no field found so must be a related manager. Which we treat the same as many to many self.many_to_many = True
def get_verbose_name(an_object, field_name, init_cap=True): """Given a model or model instance, return the verbose_name of the model's field. If init_cap is True (the default), the verbose_name will be returned with the first letter capitalized which makes the verbose_name look nicer in labels. If field_name doesn't refer to a model field, raises a FieldDoesNotExist error. """ # get_field_by_name() can raise FieldDoesNotExist which I simply propogate up to the caller. try: field = an_object._meta.get_field_by_name(field_name)[0] except TypeError: # TypeError happens if the caller is very confused and passes an unhashable type such # as {} or []. I convert that into a FieldDoesNotExist exception for simplicity. raise FieldDoesNotExist("No field named {}".format(str(field_name))) verbose_name = field.verbose_name if init_cap: verbose_name = lazy(capfirst, unicode)(verbose_name) return verbose_name
def add_date_select(self, field_name, lookup_type, order='ASC'): """ Converts the query into a date extraction query. """ try: result = self.setup_joins(field_name.split(LOOKUP_SEP), self.get_meta(), self.get_initial_alias(), False) except FieldError: raise FieldDoesNotExist("%s has no field named '%s'" % (self.model._meta.object_name, field_name)) field = result[0] assert isinstance(field, DateField), "%r isn't a DateField." \ % field.name alias = result[3][-1] select = Date((alias, field.column), lookup_type) self.clear_select_clause() self.select = [SelectInfo(select, None)] self.distinct = True self.order_by = order == 'ASC' and [1] or [-1] if field.null: self.add_filter(("%s__isnull" % field_name, False))
def get_field(self, name): """Return a field with the given name. Args: name (unicode): The name of the field. Returns: django.db.models.Field: The field with the given name. Raises: django.db.models.fields.FieldDoesNotExist: The field could not be found. """ try: return self._fields[name] except KeyError: try: return self._many_to_many[name] except KeyError: raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def add_select(self, field_name, lookup_type, order='ASC'): """ Converts the query into an extraction query. """ try: field, _, _, joins, _ = self.setup_joins( field_name.split(LOOKUP_SEP), self.get_meta(), self.get_initial_alias(), ) except FieldError: raise FieldDoesNotExist("%s has no field named '%s'" % (self.get_meta().object_name, field_name)) self._check_field(field) # overridden in DateTimeQuery alias = joins[-1] select = self._get_select((alias, field.column), lookup_type) self.clear_select_clause() self.select = [SelectInfo(select, None)] self.distinct = True self.order_by = [1] if order == 'ASC' else [-1] if field.null: self.add_filter(("%s__isnull" % field_name, False))
def recognise_relation_type(model, field_name): try: field = model._meta.get_field(field_name) if isinstance(field, ForeignKey) or isinstance( field, OneToOneField ): # OneToOneField is a subclass of ForeignKey anyway, but best not to rely on that return ('single', field.rel.to) elif isinstance(field, ManyToManyField): return ('multiple', field.rel.to) else: return ('field', None) except FieldDoesNotExist: # check reverse relations for rel in model._meta.get_all_related_objects(): if rel.get_accessor_name() == field_name: if isinstance(rel.field, OneToOneField): return ('single', rel.model) else: return ('multiple', rel.model) for rel in model._meta.get_all_related_many_to_many_objects(): if rel.get_accessor_name() == field_name: return ('multiple', rel.model) raise FieldDoesNotExist('%s has no field named %r' % (model._meta.object_name, field_name))
def _not_exists(fieldname): raise FieldDoesNotExist( '"%s" is not a ManyToManyField or a reverse ForeignKey relationship' % fieldname)
def get_field(self, name): if name not in self.fields_dict: raise FieldDoesNotExist('No field `%s` in model: %s' % (name, self.object_name)) return self.fields_dict[name]
def __new__(cls, name, bases, attrs): new_class = super(ModelDeclarativeMetaclass, cls).__new__(cls, name, bases, attrs) opts = new_class._meta if not opts.instance_loader_class: opts.instance_loader_class = ModelInstanceLoader if opts.model: model_opts = opts.model._meta declared_fields = new_class.fields field_list = [] for f in sorted(model_opts.fields + model_opts.many_to_many): if opts.fields is not None and not f.name in opts.fields: continue if opts.exclude and f.name in opts.exclude: continue if f.name in declared_fields: continue field = new_class.field_from_django_field(f.name, f, readonly=False) field_list.append((f.name, field, )) if isinstance(field.widget, widgets.ForeignKeyWidget): # field is a foreignkey, register its _id field as well name = f.get_attname() f = IntegerField(name) field = new_class.field_from_django_field(name, f, readonly=False) field_list.append((name, field)) new_class.fields.update(OrderedDict(field_list)) #add fields that follow relationships if opts.fields is not None: field_list = [] for field_name in opts.fields: if field_name in declared_fields: continue if field_name.find('__') == -1: continue model = opts.model attrs = field_name.split('__') for i, attr in enumerate(attrs): verbose_path = ".".join([opts.model.__name__] + attrs[0:i+1]) try: f = model._meta.get_field_by_name(attr)[0] except FieldDoesNotExist as e: raise FieldDoesNotExist("%s: %s has no field named '%s'" % (verbose_path, model.__name__, attr)) if i < len(attrs) - 1: # We're not at the last attribute yet, so check that # we're looking at a relation, and move on to the # next model. if isinstance(f, RelatedObject): model = f.model else: if f.rel is None: raise KeyError('%s is not a relation' % verbose_path) model = f.rel.to if isinstance(f, RelatedObject): f = f.field field = new_class.field_from_django_field(field_name, f, readonly=True) field_list.append((field_name, field)) new_class.fields.update(OrderedDict(field_list)) return new_class
def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) opts = new_class._meta if not opts.instance_loader_class: opts.instance_loader_class = ModelInstanceLoader if opts.model: model_opts = opts.model._meta declared_fields = new_class.fields field_list = [] for f in sorted(model_opts.fields + model_opts.many_to_many): if opts.fields is not None and not f.name in opts.fields: continue if opts.exclude and f.name in opts.exclude: continue if f.name in declared_fields: continue field = new_class.field_from_django_field(f.name, f, readonly=False) field_list.append(( f.name, field, )) new_class.fields.update(OrderedDict(field_list)) # add fields that follow relationships if opts.fields is not None: field_list = [] for field_name in opts.fields: if field_name in declared_fields: continue if field_name.find('__') == -1: continue model = opts.model attrs = field_name.split('__') for i, attr in enumerate(attrs): verbose_path = ".".join([opts.model.__name__] + attrs[0:i + 1]) try: f = model._meta.get_field(attr) except FieldDoesNotExist as e: logger.debug(e, exc_info=e) raise FieldDoesNotExist( "%s: %s has no field named '%s'" % (verbose_path, model.__name__, attr)) if i < len(attrs) - 1: # We're not at the last attribute yet, so check # that we're looking at a relation, and move on to # the next model. if isinstance(f, ForeignObjectRel): model = get_related_model(f) else: if get_related_model(f) is None: raise KeyError('%s is not a relation' % verbose_path) model = get_related_model(f) if isinstance(f, ForeignObjectRel): f = f.field field = new_class.field_from_django_field(field_name, f, readonly=True) field_list.append((field_name, field)) new_class.fields.update(OrderedDict(field_list)) return new_class
def calc_field_names(rel): # Extract field names from through model and stores them in # rel.through_field (so that they are sent on deconstruct and # passed to ModelState instances) tf_dict = {} if is_fake_model(rel.through): # we populate the through field dict using rel.through_fields # that was either provided or computed beforehand with the # actual model for f, k in zip(rel.through_fields, ('src', 'tgt', 'tgt_ct', 'tgt_fk')): tf_dict[k] = f rel.through._meta._field_names = tf_dict return if rel.through_fields: tf_dict['src'], tf_dict['tgt'] = \ rel.through_fields[:2] for gfk in rel.through._meta.private_fields: if gfk.name == tf_dict['tgt']: break else: raise FieldDoesNotExist( 'Generic foreign key "%s" does not exist in through ' 'model "%s"' % (tf_dict['tgt'], rel.through._meta.model_name) ) tf_dict['tgt_ct'] = gfk.ct_field tf_dict['tgt_fk'] = gfk.fk_field else: for f in rel.through._meta.fields: # ETJ DEBUG if (hasattr(f, 'rel') and f.remote_field \ and (f.remote_field.model == rel.field.model or f.remote_field.model == '%s.%s' % (rel.field.model._meta.app_label,rel.field.model._meta.object_name) or f.remote_field.model == rel.field.model._meta.object_name)): # NOTE: Original code failed on Django 1.10 # if hasattr(f, 'rel') and f.remote_field \ # and (f.remote_field.model == rel.field.model # or f.remote_field.model == '%s.%s' % ( # rel.field.model._meta.app_label, # rel.field.model._meta.object_name)): # END DEBUG tf_dict['src'] = f.name break for f in rel.through._meta.private_fields: if isinstance(f, ct.GenericForeignKey): tf_dict['tgt'] = f.name tf_dict['tgt_ct'] = f.ct_field tf_dict['tgt_fk'] = f.fk_field break if not set(tf_dict.keys()).issuperset(('src', 'tgt')): raise ValueError('Bad through model for GM2M relationship.') rel.through._meta._field_names = tf_dict # save the result in rel.through_fields so that it appears # in the deconstruction. Without that there would be no way for # a ModelState constructed from a migration to know which fields # have which function, as all virtual fields are stripped tf = [] for f in ('src', 'tgt', 'tgt_ct', 'tgt_fk'): tf.append(tf_dict[f]) rel.set_init('through_fields', tf)
def get_value(self, model, field_name, query): field_to_index = self.get_field_to_index(model, field_name) for query_field, value in query.values[:]: if field_to_index == query_field: return value raise FieldDoesNotExist('Cannot find field in query.')
def _get_seq_model_field(cms): raise FieldDoesNotExist()
def get_field_by_name(*args, **kwargs): raise FieldDoesNotExist()