Python django.db.models.fields.CharField() Examples

The following are 19 code examples of django.db.models.fields.CharField(). 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: build_search_filters.py    From openprescribing with MIT License 6 votes vote down vote up
def _build_search_filter(cls, field_name):
    if field_name == "bnf_code":
        return _build_search_filter_bnf_code_prefox()

    field = cls._meta.get_field(field_name)
    builder = {
        ForeignKey: _build_search_filter_fk,
        ManyToOneRel: _build_search_filter_rev_fk,
        OneToOneRel: _build_search_filter_rev_fk,
        fields.CharField: _build_search_filter_char,
        fields.DateField: _build_search_filter_date,
        fields.BooleanField: _build_search_filter_boolean,
        fields.DecimalField: _build_search_filter_decimal,
    }[type(field)]
    search_filter = builder(field)
    search_filter["id"] = field_name
    return search_filter 
Example #2
Source File: bigquery.py    From openprescribing with MIT License 6 votes vote down vote up
def build_schema_from_model(model):
    field_mappings = {
        model_fields.BigIntegerField: "INTEGER",
        model_fields.CharField: "STRING",
        model_fields.DateField: "DATE",
        model_fields.FloatField: "FLOAT",
        model_fields.DecimalField: "NUMERIC",
        model_fields.IntegerField: "INTEGER",
        model_fields.BooleanField: "BOOLEAN",
        model_fields.NullBooleanField: "BOOLEAN",
        model_fields.TextField: "STRING",
        related_fields.ForeignKey: "INTEGER",
        related_fields.OneToOneField: "INTEGER",
    }

    fields = [
        (f.name, field_mappings[type(f)])
        for f in model._meta.fields
        if not f.auto_created
    ]

    return build_schema(*fields) 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_field_rename_inside_atomic_block(self):
        """
        NotImplementedError is raised when a model field rename is attempted
        inside an atomic block.
        """
        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name('renamed')
        msg = (
            "Renaming the 'backends_author'.'name' column while in a "
            "transaction is not supported on SQLite < 3.26 because it would "
            "break referential integrity. Try adding `atomic = False` to the "
            "Migration class."
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            with connection.schema_editor(atomic=True) as editor:
                editor.alter_field(Author, Author._meta.get_field('name'), new_field) 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_field_rename_inside_atomic_block(self):
        """
        NotImplementedError is raised when a model field rename is attempted
        inside an atomic block.
        """
        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name('renamed')
        msg = (
            "Renaming the 'backends_author'.'name' column while in a "
            "transaction is not supported on SQLite because it would break "
            "referential integrity. Try adding `atomic = False` to the "
            "Migration class."
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            with connection.schema_editor(atomic=True) as editor:
                editor.alter_field(Author, Author._meta.get_field('name'), new_field) 
Example #5
Source File: djpeewee.py    From Quiver-alfred with MIT License 6 votes vote down vote up
def get_django_field_map(self):
        from django.db.models import fields as djf
        return [
            (djf.AutoField, PrimaryKeyField),
            (djf.BigIntegerField, BigIntegerField),
            # (djf.BinaryField, BlobField),
            (djf.BooleanField, BooleanField),
            (djf.CharField, CharField),
            (djf.DateTimeField, DateTimeField),  # Extends DateField.
            (djf.DateField, DateField),
            (djf.DecimalField, DecimalField),
            (djf.FilePathField, CharField),
            (djf.FloatField, FloatField),
            (djf.IntegerField, IntegerField),
            (djf.NullBooleanField, partial(BooleanField, null=True)),
            (djf.TextField, TextField),
            (djf.TimeField, TimeField),
            (djf.related.ForeignKey, ForeignKeyField),
        ] 
Example #6
Source File: filters.py    From django-datatables-view with MIT License 5 votes vote down vote up
def build_column_filter(column_name, column_obj, column_spec, search_value):
    search_filter = None

    # if type(column_obj.model_field) == fields.CharField:
    #     # do something special with this field

    choices = column_spec['choices']
    if column_obj.has_choices_available:

        if choices:
            # Since we're using choices (we provided a select box)
            # just use the selected key
            values = [search_value, ]
        else:
            values = column_obj.search_in_choices(search_value)

        search_filter = Q(**{column_obj.name + '__in': values})

    elif isinstance(column_obj.model_field, (models.DateTimeField, models.DateField)):
        try:
            parsed_date = parse_date(search_value)
            date_range = [parsed_date.isoformat(), parsed_date.isoformat()]
            query_param_name = column_obj.get_field_search_path()
            if isinstance(column_obj.model_field, models.DateTimeField):
                search_filter = Q(**{query_param_name + '__date__range': date_range})
            else:
                search_filter = Q(**{query_param_name + '__range': date_range})
        except ValueError:
            pass
    else:
        query_param_name = column_obj.get_field_search_path()
        #search_filters |= Q(**{query_param_name + '__istartswith': search_value})
        search_filter = Q(**{query_param_name + '__icontains': search_value})

    return search_filter 
Example #7
Source File: context.py    From django-stubs with MIT License 5 votes vote down vote up
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 #8
Source File: build_search_query.py    From openprescribing with MIT License 5 votes vote down vote up
def _build_lookup_key(cls, field_name, operator):
    field = cls._meta.get_field(field_name)
    builder = {
        ForeignKey: _build_lookup_fk,
        ManyToOneRel: _build_lookup_rev_fk,
        OneToOneRel: _build_lookup_rev_fk,
        fields.CharField: _build_lookup_char,
        fields.DateField: _build_lookup_date,
        fields.BooleanField: _build_lookup_boolean,
        fields.DecimalField: _build_lookup_decimal,
    }[type(field)]
    return builder(cls, field_name, operator) 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_data_field(self):
        field_info = self._details(Person, Person._meta.get_field('data_abstract'))
        self.assertEqual(field_info[1:], (BasePerson, True, False))
        self.assertIsInstance(field_info[0], CharField) 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_data_field(self):
        field_info = self._details(Person, Person._meta.get_field('data_abstract'))
        self.assertEqual(field_info[1:], (BasePerson, True, False))
        self.assertIsInstance(field_info[0], CharField) 
Example #11
Source File: fields.py    From django-language-field with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        # Local import so the languages aren't loaded unless they are needed.
        from .languages import LANGUAGES

        kwargs.setdefault('max_length', 3)
        kwargs.setdefault('choices', LANGUAGES)
        super(CharField, self).__init__(*args, **kwargs) 
Example #12
Source File: admin.py    From silver with Apache License 2.0 5 votes vote down vote up
def get_search_results(self, request, queryset, search_term):
        if '-' in search_term and search_term[-1].isdigit():
            return queryset \
                .annotate(_series_number=Concat(F('series'), Value('-'), F('number'),
                                                output_field=fields.CharField())) \
                .filter(_series_number=search_term), True

        return super(BillingDocumentAdmin, self).get_search_results(request, queryset, search_term) 
Example #13
Source File: admin.py    From silver with Apache License 2.0 5 votes vote down vote up
def lookups(self, request, model_admin):
        queryset = model_admin.get_queryset(request)

        proformas_queryset = Proforma.objects \
            .filter(proforma_transactions__in=queryset.distinct()) \
            .annotate(_series_number=Concat(F('series'), Value('-'), F('number'),
                                            output_field=fields.CharField())) \
            .values_list('id', '_series_number') \
            .distinct()

        return list(proformas_queryset) 
Example #14
Source File: admin.py    From silver with Apache License 2.0 5 votes vote down vote up
def lookups(self, request, model_admin):
        queryset = model_admin.get_queryset(request)

        invoices_queryset = Invoice.objects \
            .filter(invoice_transactions__in=queryset.distinct()) \
            .annotate(_series_number=Concat(F('series'), Value('-'), F('number'),
                                            output_field=fields.CharField())) \
            .values_list('id', '_series_number') \
            .distinct()

        return list(invoices_queryset) 
Example #15
Source File: admin.py    From silver with Apache License 2.0 5 votes vote down vote up
def lookups(self, request, model_admin):
        queryset = model_admin.get_queryset(request).distinct() \
            .annotate(
                _name_provider=Concat(
                    F('plan__name'), Value(' ('), F('plan__provider__name'), Value(')'),
                    output_field=fields.CharField()
                ),
        ) \
            .values_list('id', '_name_provider') \
            .distinct()

        return list(queryset) 
Example #16
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection) 
Example #17
Source File: models.py    From elasticsearch-django with MIT License 5 votes vote down vote up
def _raw_sql(self, values: List[Tuple[Union[str, int], Union[str, int]]]) -> str:
        """Prepare SQL statement consisting of a sequence of WHEN .. THEN statements."""
        if isinstance(self.model._meta.pk, CharField):
            when_clauses = " ".join(
                [self._when("'{}'".format(x), y) for (x, y) in values]
            )
        else:
            when_clauses = " ".join([self._when(x, y) for (x, y) in values])
        table_name = self.model._meta.db_table
        primary_key = self.model._meta.pk.column
        return 'SELECT CASE {}."{}" {} ELSE 0 END'.format(
            table_name, primary_key, when_clauses
        ) 
Example #18
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection) 
Example #19
Source File: edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_comparison_class(self):
        # Hide fields with hidden widget
        widget_override = self.widget_overrides().get(self.field_name, None)
        if widget_override and widget_override.is_hidden:
            return

        try:
            field = self.db_field

            if field.choices:
                return compare.ChoiceFieldComparison

            if field.is_relation:
                if isinstance(field, TaggableManager):
                    return compare.TagsFieldComparison
                elif field.many_to_many:
                    return compare.M2MFieldComparison

                return compare.ForeignObjectComparison

            if isinstance(field, RichTextField):
                return compare.RichTextFieldComparison

            if isinstance(field, (CharField, TextField)):
                return compare.TextFieldComparison

        except FieldDoesNotExist:
            pass

        return compare.FieldComparison