def contribute_to_class(self, cls, name, virtual_only=False): # We need to skip RelatedField in the mro, so we can't use `super()` Field.contribute_to_class( self, cls, name, virtual_only=virtual_only ) self.opts = cls._meta if not cls._meta.abstract and self.rel.related_name: related_name = force_text(self.rel.related_name) % { 'class': cls.__name__.lower(), 'app_label': cls._meta.app_label.lower() } self.rel.related_name = related_name for state in system_layout.allowed_values: with system_layout.as_value(state): other = self.to if other is None: # This should only happen if `cls` is not going to be # used for `state`. Just leave the null value there continue if isinstance(other, str) or other._meta.pk is None: def resolve_related_class(field, model, cls, state=state): with system_layout.as_value(state): field.to = model field.do_related_class(model, cls) add_lazy_relation(cls, self, other, resolve_related_class) else: self.do_related_class(other, cls)
def __init__(self, to, through, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be a string assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to GenericManyToManyField must be either a model or a model name" % (self.__class__.__name__, to) kwargs['verbose_name'] = kwargs.get('verbose_name', None) self.through = through kwargs['rel'] = ManyToManyRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=False, through=None# Validation will fail if ManyToManyRel uses a through table that does not have a source foreign key ) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." kwargs['serialize'] = False Field.__init__(self, **kwargs) msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def __init__(self, verbose_name=_("Tags"), help_text=_("A comma-separated list of tags."), through=None, blank=False, related_name=None, manager=_TaggableManager): Field.__init__(self, verbose_name=verbose_name, help_text=help_text, blank=blank, null=True, serialize=False) self.through = through or TaggedItem self.rel = TaggableRel(self, related_name, self.through) self.swappable = False self.manager = manager
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: to_field = to_field or to._meta.pk.name kwargs['verbose_name'] = kwargs.get('verbose_name', '') if 'edit_inline_type' in kwargs: import warnings warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.", DeprecationWarning) kwargs['edit_inline'] = kwargs.pop('edit_inline_type') kwargs['rel'] = rel_class(to, to_field, num_in_admin=kwargs.pop('num_in_admin', 3), min_num_in_admin=kwargs.pop('min_num_in_admin', None), max_num_in_admin=kwargs.pop('max_num_in_admin', None), num_extra_on_change=kwargs.pop('num_extra_on_change', 1), edit_inline=kwargs.pop('edit_inline', False), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), parent_link=kwargs.pop('parent_link', False)) Field.__init__(self, **kwargs) self.db_index = True
def contribute_to_class(self, cls, name, virtual_only=False): # We need to skip RelatedField in the mro, so we can't use `super()` Field.contribute_to_class(self, cls, name, virtual_only=virtual_only) self.opts = cls._meta if not cls._meta.abstract and self.rel.related_name: related_name = force_text(self.rel.related_name) % { 'class': cls.__name__.lower(), 'app_label': cls._meta.app_label.lower() } self.rel.related_name = related_name for state in system_layout.allowed_values: with system_layout.as_value(state): other = self.to if other is None: # This should only happen if `cls` is not going to be # used for `state`. Just leave the null value there continue if isinstance(other, str) or other._meta.pk is None: def resolve_related_class(field, model, cls, state=state): with system_layout.as_value(state): field.to = model field.do_related_class(model, cls) add_lazy_relation(cls, self, other, resolve_related_class) else: self.do_related_class(other, cls)
def autofield_init(self, *args, **kwargs): kwargs["blank"] = True Field.__init__(self, *args, **kwargs) if (django.db.connection.settings_dict["ENGINE"] == "django_spanner" and self.default == NOT_PROVIDED): self.default = gen_rand_int64
def __init__(self, to, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % ( self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance( to, basestring ), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel( to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: self.creates_table = False assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." else: self.creates_table = True Field.__init__(self, **kwargs) msg = ugettext_lazy( 'Hold down "Control", or "Command" on a Mac, to select more than one.' ) self.help_text = string_concat(self.help_text, ' ', msg)
def __init__(self, to, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, num_in_admin=kwargs.pop('num_in_admin', 0), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: self.creates_table = False assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." else: self.creates_table = True Field.__init__(self, **kwargs) msg = ugettext_lazy('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def __init__(self, to, to_field=None, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "ForeignKey(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (to, RECURSIVE_RELATIONSHIP_CONSTANT) else: to_field = to_field or to._meta.pk.name kwargs['verbose_name'] = kwargs.get('verbose_name', '') if 'edit_inline_type' in kwargs: import warnings warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.", DeprecationWarning) kwargs['edit_inline'] = kwargs.pop('edit_inline_type') kwargs['rel'] = ManyToOneRel(to, to_field, num_in_admin=kwargs.pop('num_in_admin', 3), min_num_in_admin=kwargs.pop('min_num_in_admin', None), max_num_in_admin=kwargs.pop('max_num_in_admin', None), num_extra_on_change=kwargs.pop('num_extra_on_change', 1), edit_inline=kwargs.pop('edit_inline', False), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), raw_id_admin=kwargs.pop('raw_id_admin', False)) Field.__init__(self, **kwargs) self.db_index = True
def get_schema_field(field: Field, *, depth: int = 0) -> Tuple: alias = None default = ... default_factory = None description = None title = None max_length = None python_type = None if field.is_relation: if depth > 0: return get_related_field_schema(field, depth=depth) internal_type = field.related_model._meta.pk.get_internal_type() if not field.concrete and field.auto_created or field.null: default = None if hasattr(field, "get_attname"): alias = field.get_attname() pk_type = TYPES.get(internal_type, int) if field.one_to_many or field.many_to_many: m2m_type = create_m2m_link_type(pk_type) python_type = List[m2m_type] else: python_type = pk_type else: field_options = field.deconstruct()[3] # 3 are the keywords blank = field_options.get("blank", False) null = field_options.get("null", False) max_length = field_options.get("max_length") internal_type = field.get_internal_type() python_type = TYPES[internal_type] if field.has_default(): if callable(field.default): default_factory = field.default else: default = field.default elif field.primary_key or blank or null: default = None description = field.help_text title = field.verbose_name.title() return ( python_type, FieldInfo( default, alias=alias, default_factory=default_factory, title=title, description=description, max_length=max_length, ), )
def __init__(self, verbose_name=_("Tags"), help_text=_("A comma-separated list of tags."), through=None, blank=False, related_name=None, to=None, manager=_TaggableManager): Field.__init__(self, verbose_name=verbose_name, help_text=help_text, blank=blank, null=True, serialize=False) self.through = through or TaggedItem self.rel = TaggableRel(self, related_name, self.through, to=to) self.swappable = False self.manager = manager
def __init__(self, verbose_name=_("Tags"), help_text=_("A comma-separated list of tags."), through=None, blank=False): Field.__init__(self, verbose_name=verbose_name, help_text=help_text, blank=blank) self.through = through or TaggedItem self.rel = TaggableRel(self)
def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, num_in_admin=kwargs.pop('num_in_admin', 0), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True)) self.db_table = kwargs.pop('db_table', None) Field.__init__(self, **kwargs) msg = ugettext_lazy('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def __init__(self, to, field_name, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, related_name=None, symmetrical=True, limit_choices_to=kwargs.pop('limit_choices_to', None), through=None) self.field_name = field_name kwargs['blank'] = True kwargs['editable'] = True kwargs['serialize'] = False Field.__init__(self, **kwargs)
def __init__(self, verbose_name="Bids", help_text="Bids", blank=False, related_name=None, to=None, manager=_BiddableManager): Field.__init__(self, verbose_name=verbose_name, help_text=help_text, blank=blank, null=True, serialize=False) self.manager = manager
def test_field_ordering(self): """ Field instances have a `__lt__` comparison function to define an ordering based on their creation. Prior to #17851 this ordering comparison relied on the now unsupported `__cmp__` and was assuming compared objects were both Field instances raising `AttributeError` when it should have returned `NotImplemented`. """ f1 = Field() f2 = Field(auto_created=True) f3 = Field() self.assertTrue(f2 < f1) self.assertTrue(f3 > f1) self.assertFalse(f1 == None) self.assertFalse(f2 in (None, 1, ''))
def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel( to, num_in_admin=kwargs.pop('num_in_admin', 0), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True)) self.db_table = kwargs.pop('db_table', None) Field.__init__(self, **kwargs) msg = ugettext_lazy( 'Hold down "Control", or "Command" on a Mac, to select more than one.' ) self.help_text = string_concat(self.help_text, ' ', msg)
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
def __init__(self, to, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ArrayManyToManyRel(to, limit_choices_to=kwargs.pop('limit_choices_to', None), related_name=kwargs.pop('related_name', None), manager_name=kwargs.pop('manager_name', None)) Field.__init__(self, **kwargs) msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def make_atom_delete(self, child, qn, connection): """ Turn a tuple (table_alias, column_name, db_type, lookup_type, value_annot, params) into valid SPARQL. Returns the string for the SPARQL fragment and the parameters to use for it. """ lvalue, lookup_type, value_annot, params_or_value = child if hasattr(lvalue, 'process'): try: lvalue, params = lvalue.process(lookup_type, params_or_value, connection) except EmptyShortCircuit: raise EmptyResultSet else: params = Field().get_db_prep_lookup(lookup_type, params_or_value, connection=connection, prepared=True) if isinstance(lvalue, tuple): # A direct database column lookup. field_sparql = self.sparql_for_columns(lvalue, qn, connection) else: # A smart object with an as_sparql() method. field_sparql = lvalue.as_sparql(qn, connection) if value_annot is datetime.datetime: cast_sparql = connection.ops.datetime_cast_sparql() else: cast_sparql = '%s' return '%s ?s ?p', params
class Poseidon_db_List(generics.ListAPIView): swagger_schema = None # Only staff users allowed #permission_classes = (UserPermission, ) def get_queryset(self): platform = self.kwargs['platform'] t = getModel_no_dvalqc() t._meta.db_table = 'public\".\"' + platform queryset = t.objects.all() return queryset def get_serializer_class(self): platform = self.kwargs['platform'] t = getModel_no_dvalqc() t._meta.db_table = 'public\".\"' + platform serializer_class = NoDvalqcDataSerializer serializer_class.Meta.model = t return serializer_class filter_backends = (DjangoFilterBackend, ) Field.register_lookup(NotEqual) filter_fields = { 'dt': ['lt', 'gt', 'lte', 'gte', 'icontains'], 'pres': ['lt', 'gt', 'lte', 'gte', 'in'], 'param__id': ['exact', 'ne', 'in'], }
def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) if not self.blank: if rel: # This validator makes sure FileFields work in a related context. class RequiredFileField(object): def __init__(self, other_field_names, other_file_field_name): self.other_field_names = other_field_names self.other_file_field_name = other_file_field_name self.always_test = True def __call__(self, field_data, all_data): if not all_data.get(self.other_file_field_name, False): c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, ugettext_lazy("This field is required.")) c(field_data, all_data) # First, get the core fields, if any. core_field_names = [] for f in opts.fields: if f.core and f != self: core_field_names.extend(f.get_manipulator_field_names(name_prefix)) # Now, if there are any, add the validator to this FormField. if core_field_names: field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name)) else: v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, ugettext_lazy("This field is required.")) v.always_test = True field_list[0].validator_list.append(v) field_list[0].is_required = field_list[1].is_required = False # If the raw path is passed in, validate it's under the MEDIA_ROOT. def isWithinMediaRoot(field_data, all_data): f = os.path.abspath(os.path.join(settings.MEDIA_ROOT, field_data)) if not f.startswith(os.path.abspath(os.path.normpath(settings.MEDIA_ROOT))): raise validators.ValidationError(_("Enter a valid filename.")) field_list[1].validator_list.append(isWithinMediaRoot) return field_list
def _get_lookup(self, operator, over): lookup = Field().get_db_prep_lookup(operator, over, connection=self._db_connection, prepared=True) if isinstance(lookup, (tuple, list)): return lookup[0] return lookup
class PlatformFilter(FilterSet): Field.register_lookup(NotEqual) #Field.register_lookup(NotIn) status = filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) class Meta: model = Platform fields = { #filters:'exact','ne', 'lt', 'gt', 'lte', 'gte', 'in', icontains 'id': ['exact', 'ne', 'in'], #notin 'pid': ['exact', 'ne','in'], #notin 'tspr': ['exact', 'ne'], 'type': ['exact', 'ne', 'in'], #notin 'inst': ['exact'], #einai kai kleidi gia institutions opote ftiaxnei drop down me ta institutions 'inst__id': ['exact', 'in'], 'dts': [ 'lt', 'gt', 'lte', 'gte', 'icontains'], 'dte': [ 'lt', 'gt', 'lte', 'gte', 'icontains'], 'lat': ['lt', 'gt', 'lte', 'gte'], 'lon': ['lt', 'gt', 'lte', 'gte'], 'status': [], 'params' : ['icontains'], 'platform_code': [], 'wmo': ['exact', 'ne', 'icontains'], 'pi_name' : ['icontains'], 'author' : [], 'contact' : [], 'island': [], 'pl_name' : [], 'inst_ref' : [], 'assembly_center' : ['exact', 'ne', 'in'], 'site_code' : [], 'source' : [], 'cdf_inst': ['exact'] }
def get_prep_value(self, value): """Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea. """ value = Field.get_prep_value(self, value) if isinstance(value, dict): prep_value = {} for key, val in value.items(): if isinstance(val, Expression): prep_value[key] = val elif val is not None: prep_value[key] = str(val) else: prep_value[key] = val value = prep_value if isinstance(value, list): value = [str(item) for item in value] return value
def formfield(self, **kwargs): defaults = { 'form_class': BitFormField, 'choices': self.flags, } defaults.update(kwargs) return Field.formfield(self, **defaults)
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = rel_class(to, to_field, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), parent_link=kwargs.pop('parent_link', False)) Field.__init__(self, **kwargs) self.db_index = True
def test_custom_lookup_in_search_fields(self): band = Group.objects.create(name='The Hype') concert = Concert.objects.create(name='Woodstock', group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ['group__name__cc'] Field.register_lookup(Contains, 'cc') try: request = self.factory.get('/', data={SEARCH_VAR: 'Hype'}) cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get('/', data={SEARCH_VAR: 'Woodstock'}) cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) finally: Field._unregister_lookup(Contains, 'cc')
def field_instances(self): fields = list(self.meta.fields) for field in self.dynamic_fields: fields.append( Field(name=field, verbose_name=field.replace('_', ' '), editable=False)) return fields
def make_atom(self, child, qn): """ Turn a tuple (table_alias, field_name, field_class, lookup_type, value) into valid SQL. Returns the string for the SQL fragment and the parameters to use for it. """ table_alias, name, field, lookup_type, value = child if table_alias: lhs = '%s.%s' % (qn(table_alias), qn(name)) else: lhs = qn(name) db_type = field and field.db_type() or None field_sql = connection.ops.field_cast_sql(db_type) % lhs if isinstance(value, datetime.datetime): cast_sql = connection.ops.datetime_cast_sql() else: cast_sql = '%s' if field: params = field.get_db_prep_lookup(lookup_type, value) else: params = Field().get_db_prep_lookup(lookup_type, value) if isinstance(params, QueryWrapper): extra, params = params.data else: extra = '' if lookup_type in connection.operators: format = "%s %%s %s" % (connection.ops.lookup_cast(lookup_type), extra) return (format % (field_sql, connection.operators[lookup_type] % cast_sql), params) if lookup_type == 'in': if not value: raise EmptyResultSet if extra: return ('%s IN %s' % (field_sql, extra), params) return ('%s IN (%s)' % (field_sql, ', '.join(['%s'] * len(value))), params) elif lookup_type in ('range', 'year'): return ('%s BETWEEN %%s and %%s' % field_sql, params) elif lookup_type in ('month', 'day'): return ('%s = %%s' % connection.ops.date_extract_sql(lookup_type, field_sql), params) elif lookup_type == 'isnull': return ('%s IS %sNULL' % (field_sql, (not value and 'NOT ' or '')), params) elif lookup_type == 'search': return (connection.ops.fulltext_search_sql(field_sql), params) elif lookup_type in ('regex', 'iregex'): return connection.ops.regex_lookup(lookup_type) % (field_sql, cast_sql), params raise TypeError('Invalid lookup_type: %r' % lookup_type)
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) to_field = to_field or to._meta.pk.name kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = rel_class(to, to_field, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), parent_link=kwargs.pop('parent_link', False)) Field.__init__(self, **kwargs) self.db_index = True
def formfield(self, **kwargs): defaults = { 'form_class': forms.ShapefileField, 'max_length': self.max_length } if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) return Field.formfield(self, **defaults)
def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, num_in_admin=kwargs.pop('num_in_admin', 0), related_name=kwargs.pop('related_name', None), filter_interface=kwargs.pop('filter_interface', None), limit_choices_to=kwargs.pop('limit_choices_to', None), raw_id_admin=kwargs.pop('raw_id_admin', False), symmetrical=kwargs.pop('symmetrical', True)) self.db_table = kwargs.pop('db_table', None) if kwargs["rel"].raw_id_admin: kwargs.setdefault("validator_list", []).append(self.isValidIDList) Field.__init__(self, **kwargs) if self.rel.raw_id_admin: msg = ugettext_lazy('Separate multiple IDs with commas.') else: msg = ugettext_lazy('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def value_to_string(self, obj): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # we have to check that the length of choices is *2*, not 1, # because SelectFields always have an initial "blank" value. if not self.blank and self.choices: choice_list = self.get_choices_default() if len(choice_list) == 2: return smart_unicode(choice_list[1][0]) return Field.value_to_string(self, obj)
def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, num_in_admin=kwargs.pop('num_in_admin', 0), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: self.creates_table = False assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." else: self.creates_table = True Field.__init__(self, **kwargs) msg = ugettext_lazy('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg)
def flatten_data(self, follow, obj=None): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # we have to check that the length of choices is *2*, not 1, # because SelectFields always have an initial "blank" value. if not self.blank and self.choices: choice_list = self.get_choices_default() if len(choice_list) == 2: return {self.attname: choice_list[1][0]} return Field.flatten_data(self, follow, obj)
class Cdf_InstitutionFilter(FilterSet): Field.register_lookup(NotEqual) #Field.register_lookup(NotIn) class Meta: model = Cdf_Institution fields = { #filters:'exact','ne', 'lt', 'gt', 'lte', 'gte', 'in', icontains 'id': ['exact', 'ne', 'in'], #notin 'name' : ['exact', 'ne', 'icontains'], 'inst_id' : ['exact', 'in'] }
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = rel_class(to, to_field, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), parent_link=kwargs.pop('parent_link', False)) Field.__init__(self, **kwargs) self.db_index = True
def get_field_nullability(self, field: Field, method: Optional[str]) -> bool: nullable = field.null if not nullable and isinstance(field, CharField) and field.blank: return True if method == '__init__': if field.primary_key or isinstance(field, ForeignKey): return True if method == 'create': if isinstance(field, AutoField): return True if field.has_default(): return True return nullable
def __init__(self, to, field_name, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) m2m_rel_kwargs = { 'related_name': None, 'symmetrical': True, 'limit_choices_to': kwargs.pop('limit_choices_to', None), 'through': None, } if django.VERSION[:2] >= (1, 7): m2m_rel_kwargs['through'] = FalseThrough() if django.VERSION < (1, 8): kwargs['rel'] = ManyToManyRel(to, **m2m_rel_kwargs) else: kwargs['rel'] = ManyToManyRel(self, to, **m2m_rel_kwargs) self.field_name = field_name kwargs['blank'] = True kwargs['editable'] = True kwargs['serialize'] = False Field.__init__(self, **kwargs)
class InstitutionFilter(FilterSet): Field.register_lookup(NotEqual) #Field.register_lookup(NotIn) class Meta: model = Institution fields = { #filters:'exact','ne', 'lt', 'gt', 'lte', 'gte', 'in', icontains 'id': ['exact', 'ne', 'in'], #notin 'name_native' : ['exact', 'ne', 'icontains'], 'abrv' : ['exact', 'ne', 'in', 'icontains'], #notin 'country' : ['exact', 'ne', 'in', 'icontains'], #notin 'cdf_name' : [] }
class DeepObservDataList(generics.ListAPIView): """ View to list Deep Observer's data. * Requires token authentication. get: Return a list of all the deep observer's data. """ swagger_schema = None authentication_classes = [OAuth2Authentication] permission_classes = [TokenHasScope] required_scopes = ['user'] def get_queryset(self): platform = self.kwargs['platform'] t = DeepObservgetModel() t._meta.db_table = 'data\".\"' + platform queryset = t.objects.all() return queryset def get_serializer_class(self): platform = self.kwargs['platform'] t = DeepObservgetModel() t._meta.db_table = 'data\".\"' + platform serializer_class = DeepObservDataSerializer serializer_class.Meta.model = t return serializer_class filter_backends = ( DjangoFilterBackend, OrderingFilter, ) Field.register_lookup(NotEqual) filter_fields = { # available filters:'exact','ne', 'lt', 'gt', 'lte', 'gte', 'in', icontains 'id': ['exact', 'ne', 'in'], # notin 'dt': ['lt', 'gt', 'lte', 'gte', 'icontains'], 'lat': ['lt', 'gt', 'lte', 'gte'], 'lon': ['lt', 'gt', 'lte', 'gte'], 'posqc': ['exact', 'ne', 'in', 'lt', 'gt', 'lte', 'gte'], # notin 'pres': ['lt', 'gt', 'lte', 'gte'], 'presqc': ['exact', 'ne', 'in', 'lt', 'gt', 'lte', 'gte'], # notin 'param': ['exact'], 'param__id': ['exact', 'ne', 'in'], # notin 'val': ['lt', 'gt', 'lte', 'gte'], 'valqc': ['exact', 'ne', 'in', 'lt', 'gt', 'lte', 'gte'] # notin } ordering_fields = ['id']
def formfield(self, **kwargs): db = kwargs.pop('using', None) if isinstance(self.rel.to, six.string_types): raise ValueError("Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.rel.to)) defaults = { 'queryset': self.rel.to._default_manager.using(db), 'to_field_name': self.rel.field_name, 'form_class': forms.AddressSelect2Field, 'data_view': FIAS_SUGGEST_VIEW, } defaults.update(kwargs) return Field.formfield(self, **defaults)
def __init__(self, to=None, **kwargs): if not to: to = PluploadImage try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) # Python 2.6 and earlier require dictionary keys to be of str type, # not unicode and class names must be ASCII (in Python 2.x), so we # forcibly coerce it here (breaks early if there's a problem). to = str(to) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', to==RECURSIVE_RELATIONSHIP_CONSTANT), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." Field.__init__(self, **kwargs)
def flatten_data(self, follow, obj=None): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # (radio_admin=False), we have to check that the length of choices # is *2*, not 1, because SelectFields always have an initial # "blank" value. Otherwise (radio_admin=True), we check that the # length is 1. if not self.blank and (not self.rel.raw_id_admin or self.choices): choice_list = self.get_choices_default() if self.radio_admin and len(choice_list) == 1: return {self.attname: choice_list[0][0]} if not self.radio_admin and len(choice_list) == 2: return {self.attname: choice_list[1][0]} return Field.flatten_data(self, follow, obj)
def __init__(self, verbose_name=_("Tags"), help_text=_("A comma-separated list of tags."), through=None, blank=False, related_name=None, to=None, manager=_TaggableManager): ''' copy from taggit.managers.py taggit version: 0.17.0 just because the original one doesnot support serializable by default ''' self.through = through or TaggedItem self.swappable = False self.manager = manager rel = TaggableRel(self, related_name, self.through, to=to) Field.__init__( self, verbose_name=verbose_name, help_text=help_text, blank=blank, null=True, serialize=True, # make it serialize-able rel=rel, )
def __init__(self, verbose_name=_("Tags"), help_text=_("输入标签以空格或者,作为分隔符"), through=None, blank=False, related_name=None, to=None, manager=_TaggableManager): self.through = through or TaggedItem self.swappable = False self.manager = manager rel = TaggableRel(self, related_name, self.through, to=to) Field.__init__( self, verbose_name=verbose_name, help_text=help_text, blank=blank, null=True, serialize=False, rel=rel, )
def __init__(self, to, field_name, **kwargs): is_migration = kwargs.pop('is_migration', False) kwargs['verbose_name'] = kwargs.get('verbose_name', None) m2m_rel_kwargs = { 'related_name': None, 'symmetrical': True, 'limit_choices_to': kwargs.pop('limit_choices_to', None), 'through': None, } if is_migration: m2m_rel_kwargs['through'] = None self.many_to_many = False else: m2m_rel_kwargs['through'] = FalseThrough() kwargs['rel'] = ManyToManyRel(self, to, **m2m_rel_kwargs) self.field_name = field_name kwargs['blank'] = True kwargs['editable'] = True kwargs['serialize'] = False Field.__init__(self, **kwargs)
def check(self, **kwargs): errors = Field.check(self, **kwargs) errors.extend(self._check_related_name_is_valid()) for state in system_layout.allowed_values: with system_layout.as_value(state): if self.to is None: # This should only happen if `cls` is not going to be used # for `state`. Thus, we can skip all of these checks continue state_errors = [] state_errors.extend(self._check_relation_model_exists()) state_errors.extend(self._check_referencing_to_swapped_model()) state_errors.extend(self._check_clashes()) for err in state_errors: err.msg = 'With state {}: '.format(state) + err.msg errors.extend(state_errors) return errors
def formfield(self, form_class=BitFormField, **kwargs): choices = [(k, self.labels[self.flags.index(k)]) for k in self.flags] return Field.formfield(self, form_class, choices=choices, **kwargs)
def formfield(self, form_class=BitFormField, **kwargs): choices = [(f, f) for f in self.flags] return Field.formfield(self, form_class, choices=choices, **kwargs)
def make_atom(self, child, qn, connection): """ Turn a tuple (table_alias, column_name, db_type, lookup_type, value_annot, params) into valid SQL. Returns the string for the SQL fragment and the parameters to use for it. """ lvalue, lookup_type, value_annot, params_or_value = child if hasattr(lvalue, "process"): try: lvalue, params = lvalue.process(lookup_type, params_or_value, connection) except EmptyShortCircuit: raise EmptyResultSet else: params = Field().get_db_prep_lookup(lookup_type, params_or_value, connection=connection, prepared=True) if isinstance(lvalue, tuple): # A direct database column lookup. field_sql = self.sql_for_columns(lvalue, qn, connection) else: # A smart object with an as_sql() method. field_sql = lvalue.as_sql(qn, connection) if value_annot is datetime.datetime: cast_sql = connection.ops.datetime_cast_sql() else: cast_sql = "%s" if hasattr(params, "as_sql"): extra, params = params.as_sql(qn, connection) cast_sql = "" else: extra = "" if ( len(params) == 1 and params[0] == "" and lookup_type == "exact" and connection.features.interprets_empty_strings_as_nulls ): lookup_type = "isnull" value_annot = True if lookup_type in connection.operators: format = "%s %%s %%s" % (connection.ops.lookup_cast(lookup_type),) return (format % (field_sql, connection.operators[lookup_type] % cast_sql, extra), params) if lookup_type == "in": if not value_annot: raise EmptyResultSet if extra: return ("%s IN %s" % (field_sql, extra), params) return ("%s IN (%s)" % (field_sql, ", ".join(["%s"] * len(params))), params) elif lookup_type in ("range", "year"): return ("%s BETWEEN %%s and %%s" % field_sql, params) elif lookup_type in ("month", "day", "week_day"): return ("%s = %%s" % connection.ops.date_extract_sql(lookup_type, field_sql), params) elif lookup_type == "isnull": return ("%s IS %sNULL" % (field_sql, (not value_annot and "NOT " or "")), ()) elif lookup_type == "search": return (connection.ops.fulltext_search_sql(field_sql), params) elif lookup_type in ("regex", "iregex"): return connection.ops.regex_lookup(lookup_type) % (field_sql, cast_sql), params raise TypeError("Invalid lookup_type: %r" % lookup_type)
return lhs_sql, list(params) def as_sql(self, compiler, connection): lhs_sql, params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params.extend(rhs_params) rhs_sql = self.get_rhs_op(connection, rhs_sql) return '%s %s' % (lhs_sql, rhs_sql), params def get_rhs_op(self, connection, rhs): return connection.operators[self.lookup_name] % rhs class Exact(BuiltinLookup): lookup_name = 'exact' Field.register_lookup(Exact) class IExact(BuiltinLookup): lookup_name = 'iexact' def process_rhs(self, qn, connection): rhs, params = super(IExact, self).process_rhs(qn, connection) if params: params[0] = connection.ops.prep_for_iexact_query(params[0]) return rhs, params Field.register_lookup(IExact)
def get_choices_default(self): return Field.get_choices(self, include_blank=False)