Python django.db.models.fields.Field() Examples
The following are 30
code examples of django.db.models.fields.Field().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.db.models.fields
, or try the search function
.
Example #1
Source File: where.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def process(self, lookup_type, value, connection): """ Returns a tuple of data suitable for inclusion in a WhereNode instance. """ # Because of circular imports, we need to import this here. from django.db.models.base import ObjectDoesNotExist try: if self.field: params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True) db_type = self.field.db_type(connection=connection) else: # This branch is used at times when we add a comparison to NULL # (we don't really want to waste time looking up the associated # field object at the calling location). params = Field().get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True) db_type = None except ObjectDoesNotExist: raise EmptyShortCircuit return (self.alias, self.col, db_type), params
Example #2
Source File: helpers.py From django-stubs with MIT License | 6 votes |
def get_private_descriptor_type(type_info: TypeInfo, private_field_name: str, is_nullable: bool) -> MypyType: """ Return declared type of type_info's private_field_name (used for private Field attributes)""" sym = type_info.get(private_field_name) if sym is None: return AnyType(TypeOfAny.explicit) node = sym.node if isinstance(node, Var): descriptor_type = node.type if descriptor_type is None: return AnyType(TypeOfAny.explicit) if is_nullable: descriptor_type = make_optional(descriptor_type) return descriptor_type return AnyType(TypeOfAny.explicit)
Example #3
Source File: context.py From django-stubs with MIT License | 6 votes |
def _resolve_field_from_parts(self, field_parts: Iterable[str], model_cls: Type[Model] ) -> Union[Field, ForeignObjectRel]: currently_observed_model = model_cls field = None for field_part in field_parts: if field_part == 'pk': field = self.get_primary_key_field(currently_observed_model) continue field = currently_observed_model._meta.get_field(field_part) if isinstance(field, RelatedField): currently_observed_model = field.related_model model_name = currently_observed_model._meta.model_name if (model_name is not None and field_part == (model_name + '_id')): field = self.get_primary_key_field(currently_observed_model) if isinstance(field, ForeignObjectRel): currently_observed_model = field.related_model assert field is not None return field
Example #4
Source File: context.py From django-stubs with MIT License | 6 votes |
def get_field_get_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType: """ Get a type of __get__ for this specific Django field. """ field_info = helpers.lookup_class_typeinfo(api, field.__class__) if field_info is None: return AnyType(TypeOfAny.unannotated) is_nullable = self.get_field_nullability(field, method) if isinstance(field, RelatedField): related_model_cls = self.get_field_related_model_cls(field) if related_model_cls is None: return AnyType(TypeOfAny.from_error) if method == 'values': primary_key_field = self.get_primary_key_field(related_model_cls) return self.get_field_get_type(api, primary_key_field, method=method) model_info = helpers.lookup_class_typeinfo(api, related_model_cls) if model_info is None: return AnyType(TypeOfAny.unannotated) return Instance(model_info, []) else: return helpers.get_private_descriptor_type(field_info, '_pyi_private_get_type', is_nullable=is_nullable)
Example #5
Source File: context.py From django-stubs with MIT License | 6 votes |
def get_field_set_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType: """ Get a type of __set__ for this specific Django field. """ target_field = field if isinstance(field, ForeignKey): target_field = field.target_field field_info = helpers.lookup_class_typeinfo(api, target_field.__class__) if field_info is None: return AnyType(TypeOfAny.from_error) field_set_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_set_type', is_nullable=self.get_field_nullability(field, method)) if isinstance(target_field, ArrayField): argument_field_type = self.get_field_set_type(api, target_field.base_field, method=method) field_set_type = helpers.convert_any_to_type(field_set_type, argument_field_type) return field_set_type
Example #6
Source File: context.py From django-stubs with MIT License | 6 votes |
def get_field_lookup_exact_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel]) -> MypyType: if isinstance(field, (RelatedField, ForeignObjectRel)): related_model_cls = field.related_model primary_key_field = self.get_primary_key_field(related_model_cls) primary_key_type = self.get_field_get_type(api, primary_key_field, method='init') rel_model_info = helpers.lookup_class_typeinfo(api, related_model_cls) if rel_model_info is None: return AnyType(TypeOfAny.explicit) model_and_primary_key_type = UnionType.make_union([Instance(rel_model_info, []), primary_key_type]) return helpers.make_optional(model_and_primary_key_type) field_info = helpers.lookup_class_typeinfo(api, field.__class__) if field_info is None: return AnyType(TypeOfAny.explicit) return helpers.get_private_descriptor_type(field_info, '_pyi_lookup_exact_type', is_nullable=field.null)
Example #7
Source File: where.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def process(self, lookup_type, value, connection): """ Returns a tuple of data suitable for inclusion in a WhereNode instance. """ # Because of circular imports, we need to import this here. from django.db.models.base import ObjectDoesNotExist try: if self.field: params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True) db_type = self.field.db_type(connection=connection) else: # This branch is used at times when we add a comparison to NULL # (we don't really want to waste time looking up the associated # field object at the calling location). params = Field().get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True) db_type = None except ObjectDoesNotExist: raise EmptyShortCircuit return (self.alias, self.col, db_type), params
Example #8
Source File: fields.py From django-stubs with MIT License | 6 votes |
def _get_current_field_from_assignment(ctx: FunctionContext, django_context: DjangoContext) -> Optional[Field]: outer_model_info = helpers.get_typechecker_api(ctx).scope.active_class() if (outer_model_info is None or not helpers.is_model_subclass_info(outer_model_info, django_context)): return None field_name = None for stmt in outer_model_info.defn.defs.body: if isinstance(stmt, AssignmentStmt): if stmt.rvalue == ctx.context: if not isinstance(stmt.lvalues[0], NameExpr): return None field_name = stmt.lvalues[0].name break if field_name is None: return None model_cls = django_context.get_model_class_by_fullname(outer_model_info.fullname) if model_cls is None: return None current_field = model_cls._meta.get_field(field_name) return current_field
Example #9
Source File: context.py From django-stubs with MIT License | 5 votes |
def get_primary_key_field(self, model_cls: Type[Model]) -> Field: for field in model_cls._meta.get_fields(): if isinstance(field, Field): if field.primary_key: return field raise ValueError('No primary key defined')
Example #10
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def _details(self, current_model, relation): direct = isinstance(relation, Field) or isinstance(relation, GenericForeignKey) model = relation.model._meta.concrete_model if model == current_model: model = None field = relation if direct else relation.field return relation, model, direct, bool(field.many_to_many) # many_to_many can be None
Example #11
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_local_fields(self): def is_data_field(f): return isinstance(f, Field) and not f.many_to_many for model, expected_result in TEST_RESULTS['local_fields'].items(): fields = model._meta.local_fields self.assertEqual([f.attname for f in fields], expected_result) for f in fields: self.assertEqual(f.model, model) self.assertTrue(is_data_field(f))
Example #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def _details(self, current_model, relation): direct = isinstance(relation, Field) or isinstance(relation, GenericForeignKey) model = relation.model._meta.concrete_model if model == current_model: model = None field = relation if direct else relation.field return relation, model, direct, bool(field.many_to_many) # many_to_many can be None
Example #13
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_local_fields(self): def is_data_field(f): return isinstance(f, Field) and not f.many_to_many for model, expected_result in TEST_RESULTS['local_fields'].items(): fields = model._meta.local_fields self.assertEqual([f.attname for f in fields], expected_result) for f in fields: self.assertEqual(f.model, model) self.assertTrue(is_data_field(f))
Example #14
Source File: context.py From django-stubs with MIT License | 5 votes |
def get_model_fields(self, model_cls: Type[Model]) -> Iterator[Field]: for field in model_cls._meta.get_fields(): if isinstance(field, Field): yield field
Example #15
Source File: serializers.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def _get_model_fields(self, field_names, declared_fields, extra_kwargs): """ Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of 'model field name' -> 'model field'. Used internally by `get_uniqueness_field_options`. """ model = getattr(self.Meta, 'model') model_fields = {} for field_name in field_names: if field_name in declared_fields: # If the field is declared on the serializer field = declared_fields[field_name] source = field.source or field_name else: try: source = extra_kwargs[field_name]['source'] except KeyError: source = field_name if '.' in source or source == '*': # Model fields will always have a simple source mapping, # they can't be nested attribute lookups. continue try: field = model._meta.get_field(source) if isinstance(field, DjangoModelField): model_fields[source] = field except FieldDoesNotExist: pass return model_fields # Determine the validators to apply...
Example #16
Source File: context.py From django-stubs with MIT License | 5 votes |
def get_field_nullability(self, field: Union[Field, ForeignObjectRel], method: Optional[str]) -> bool: nullable = field.null if not nullable and isinstance(field, CharField) and field.blank: return True if method == '__init__': if ((isinstance(field, Field) and field.primary_key) or isinstance(field, ForeignKey)): return True if method == 'create': if isinstance(field, AutoField): return True if isinstance(field, Field) and field.has_default(): return True return nullable
Example #17
Source File: context.py From django-stubs with MIT License | 5 votes |
def resolve_lookup_into_field(self, model_cls: Type[Model], lookup: str) -> Union[Field, ForeignObjectRel]: query = Query(model_cls) lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup) if lookup_parts: raise LookupsAreUnsupported() return self._resolve_field_from_parts(field_parts, model_cls)
Example #18
Source File: helpers.py From django-stubs with MIT License | 5 votes |
def get_field_lookup_exact_type(api: TypeChecker, field: Field) -> MypyType: if isinstance(field, (RelatedField, ForeignObjectRel)): lookup_type_class = field.related_model rel_model_info = lookup_class_typeinfo(api, lookup_type_class) if rel_model_info is None: return AnyType(TypeOfAny.from_error) return make_optional(Instance(rel_model_info, [])) field_info = lookup_class_typeinfo(api, field.__class__) if field_info is None: return AnyType(TypeOfAny.explicit) return get_private_descriptor_type(field_info, '_pyi_lookup_exact_type', is_nullable=field.null)
Example #19
Source File: expressions.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def _prepare(self): """ Hook used by Field.get_prep_lookup() to do custom preparation. """ return self
Example #20
Source File: expressions.py From python2017 with MIT License | 5 votes |
def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super(RawSQL, self).__init__(output_field=output_field)
Example #21
Source File: query.py From openhgsenti with Apache License 2.0 | 5 votes |
def num_geom(self, **kwargs): """ Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None. """ return self._spatial_attribute('num_geom', {}, **kwargs)
Example #22
Source File: fields.py From openhgsenti with Apache License 2.0 | 5 votes |
def get_srid(self, geom): """ Returns the default SRID for the given geometry, taking into account the SRID set for the field. For example, if the input geometry has no SRID, then that of the field will be returned. """ gsrid = geom.srid # SRID of given geometry. if gsrid is None or self.srid == -1 or (gsrid == -1 and self.srid != -1): return self.srid else: return gsrid # ### Routines overloaded from Field ###
Example #23
Source File: expressions.py From openhgsenti with Apache License 2.0 | 5 votes |
def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super(RawSQL, self).__init__(output_field=output_field)
Example #24
Source File: expressions.py From openhgsenti with Apache License 2.0 | 5 votes |
def _prepare(self): """ Hook used by Field.get_prep_lookup() to do custom preparation. """ return self
Example #25
Source File: expressions.py From python with Apache License 2.0 | 5 votes |
def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super(RawSQL, self).__init__(output_field=output_field)
Example #26
Source File: expressions.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super().__init__(output_field=output_field)
Example #27
Source File: tests.py From django-cassandra-engine with BSD 2-Clause "Simplified" License | 5 votes |
def test_local_fields(self): def is_data_field(f): return isinstance(f, Field) and not f.many_to_many for model, expected_result in TEST_RESULTS['local_fields'].items(): fields = model._meta.local_fields self.assertEqual([f.attname for f in fields], expected_result) for f in fields: self.assertEqual(f.model, model) self.assertTrue(is_data_field(f))
Example #28
Source File: tests.py From django-cassandra-engine with BSD 2-Clause "Simplified" License | 5 votes |
def _details(self, current_model, relation): direct = isinstance(relation, Field) or isinstance(relation, GenericForeignKey) model = relation.model._meta.concrete_model if model == current_model: model = None field = relation if direct else relation.field return relation, model, direct, bool(field.many_to_many) # many_to_many can be None
Example #29
Source File: expressions.py From bioforum with MIT License | 5 votes |
def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super().__init__(output_field=output_field)
Example #30
Source File: query.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def num_geom(self, **kwargs): """ Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None. """ return self._spatial_attribute('num_geom', {}, **kwargs)