Python django.db.models.IntegerField() Examples

The following are code examples for showing how to use django.db.models.IntegerField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: midnight   Author: webadmin87   File: midnight_catalog.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def catalog_sections(context, slug=None, level=3, **kwargs):
    """
    Отображает иерерхический список категорий каталога.
    Для каждой категории отображается количество содержащегося в ней товара.

    Пример использования::

        {% catalog_sections 'section_slug' 2 class='catalog-class' %}

    :param context: контекст
    :param slug: символьный код родительской категории, если не задан, отображается вся иерархия
    :param level: отображаемый уровень вложенности
    :param kwargs: html атрибуты оборачивающего тега
    :return:
    """
    count_products = Count(Case(When(product__active=True, then=Value(1)), output_field=IntegerField()))
    if slug is None:
        sections = Section.objects.annotate(product__count=count_products).all()
        max_level = level - 1
    else:
        section = Section.objects.get(slug=slug)
        sections = section.get_descendants().annotate(product__count=count_products).all()
        max_level = section.level + level
    mark_current_menus(sections, context['request'].path_info)
    return {'sections': sections, 'max_level': max_level, 'data': kwargs} 
Example 2
Project: patch-friend   Author: catalyst   File: views.py    GNU General Public License v3.0 6 votes vote down vote up
def get_queryset(self, **kwargs):
        queryset = super(HostIndexView, self).get_queryset(**kwargs)
        if 'customer' in self.request.GET and len(self.request.GET['customer']) > 0:
            queryset = queryset.filter(customer__name=self.request.GET['customer'])

        queryset = queryset.annotate(
            problem_count=Coalesce(Subquery(
                Problem.objects.filter(
                    fixed__isnull=True,
                    host=OuterRef('pk')
                ).values('host')
                .annotate(cnt=Count('pk'))
                .values('cnt'),
                output_field=IntegerField()
            ), 0)
        ).order_by('-problem_count')

        return queryset 
Example 3
Project: django-atom   Author: ad-m   File: generate_factory.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_creator_for_field(self, name, field, model):
        if isinstance(field, models.AutoField):
            return False
        if isinstance(field, models.ForeignKey):
            return 'factory.SubFactory("{}")'.format(self.get_subfactory_path(field.related_model))
        if isinstance(field, models.CharField):
            return 'factory.Sequence("{0}-{1}-{{0}}".format)'.format(self.safe_name(model.__name__), self.safe_name(name))
        if isinstance(field, models.TextField):
            return "factory.fuzzy.FuzzyText()"
        if isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return "factory.Sequence(lambda n: n % 2 == 0)"
        if isinstance(field, (models.IntegerField, models.SmallIntegerField)):
            return "factory.Sequence(lambda n: n)"
        if isinstance(field, (models.DateTimeField)):
            if field.__class__.__name__ in ['AutoLastModifiedField', 'AutoCreatedField']:  # django-model-utils fields
                return False
            return "factory.fuzzy.FuzzyNaiveDateTime(datetime.datetime(2008, 1, 1))"
        return "UNKNOWN  # TODO: {}".format(field.__class__.__name__) 
Example 4
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 6 votes vote down vote up
def test_signal_handler_raises_no_error_on_empty_field(self):
        class NullableFieldModel(models.Model):
            some_field = models.IntegerField(null=True, blank=True)

            @cleans_field('tests.NullableFieldModel.some_field')
            def clean_some_field(self, some_field):
                return some_field + 1 if some_field else 1

        dummy = NullableFieldModel(some_field=None)
        try:
            pre_save.send(dummy.__class__, instance=dummy)
        except Exception as error:
            self.fail(
                'Sending pre_save signal resulted in unexpected error:\n\t'
                '{error}'.format(error=str(error))
            ) 
Example 5
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 6 votes vote down vote up
def test_signal_handler_raises_no_error_on_empty_field(self):
        class NullableFieldContextModel(models.Model):
            field = models.IntegerField(null=True, blank=True)

            @cleans_field_with_context('tests.NullableFieldContextModel.field')
            def clean_field(self, field, data):
                return field + 1 if field else 1

        dummy = NullableFieldContextModel(field=None)
        try:
            pre_save.send(dummy.__class__, instance=dummy)
        except Exception as error:
            self.fail(
                'Sending pre_save signal resulted in unexpected error:\n\t'
                '{error}'.format(error=str(error))
            ) 
Example 6
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 6 votes vote down vote up
def test_multiple_cleaners_for_single_field(self):
        class MultipleCleanersModel(models.Model):
            some_field = models.IntegerField()
            other = models.IntegerField()

            @cleans_field('tests.MultipleCleanersModel.some_field')
            def add_one(self, some_field):
                return some_field + 1

            @cleans_field('tests.MultipleCleanersModel.some_field')
            def add_two(self, some_field):
                return some_field + 2

            @cleans_field_with_context('tests.MultipleCleanersModel.other')
            def add_three(self, other_field, data):
                return other_field + 3 if data['some_field'] else other_field

            @cleans_field_with_context('tests.MultipleCleanersModel.other')
            def add_four(self, other_field, data):
                return other_field + 4 if data['some_field'] else other_field

        dummy = MultipleCleanersModel(some_field=5, other=6)
        pre_save.send(dummy.__class__, instance=dummy)
        self.assertEqual(dummy.some_field, 8)
        self.assertEqual(dummy.other, 13) 
Example 7
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 6 votes vote down vote up
def test_single_cleaner_for_multiple_fields(self):
        class MultipleFieldsModel(models.Model):
            field_1 = models.IntegerField()
            field_2 = models.IntegerField()
            field_3 = models.IntegerField()
            field_4 = models.IntegerField()

            @cleans_field('tests.MultipleFieldsModel.field_1')
            @cleans_field('tests.MultipleFieldsModel.field_2')
            def clean_integer_field(self, value):
                return value + 1

            @cleans_field_with_context('tests.MultipleFieldsModel.field_3')
            @cleans_field_with_context('tests.MultipleFieldsModel.field_4')
            def clean_integer_field_with_context(self, value, data):
                return value + 1 if data['field_1'] != 0 else value

        dummy = MultipleFieldsModel(field_1=1, field_2=2, field_3=3, field_4=4)
        pre_save.send(dummy.__class__, instance=dummy)
        self.assertEqual(dummy.field_1, 2)
        self.assertEqual(dummy.field_2, 3)
        self.assertEqual(dummy.field_3, 4)
        self.assertEqual(dummy.field_4, 5) 
Example 8
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 6 votes vote down vote up
def test_staticmethod_cleaner(self):
        class StaticCleanerModel(models.Model):
            some_field = models.IntegerField()
            other_field = models.IntegerField()

            @staticmethod
            @cleans_field('tests.StaticCleanerModel.some_field')
            def clean_some_field(some_field):
                return some_field + 1

            @staticmethod
            @cleans_field_with_context('tests.StaticCleanerModel.other_field')
            def clean_other_field(other_field, data):
                return other_field + 1 if data['some_field'] != 0 else 1

        dummy = StaticCleanerModel(some_field=5, other_field=6)
        pre_save.send(dummy.__class__, instance=dummy)
        self.assertEqual(dummy.some_field, 6)
        self.assertEqual(dummy.other_field, 7) 
Example 9
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 6 votes vote down vote up
def test_independent_function_cleaner(self):
        class NoCleanerModel(models.Model):
            some_field = models.IntegerField()
            other_field = models.IntegerField()

        @cleans_field('tests.NoCleanerModel.some_field')
        def clean_some_field(some_field):
            return some_field + 1

        @cleans_field_with_context('tests.NoCleanerModel.other_field')
        def clean_other_field(other_field, data):
            return other_field + 1 if data['some_field'] != 0 else other_field

        dummy = NoCleanerModel(some_field=5, other_field=6)
        pre_save.send(dummy.__class__, instance=dummy)
        self.assertEqual(dummy.some_field, 6)
        self.assertEqual(dummy.other_field, 7) 
Example 10
Project: django-clean-fields   Author: lamarmeigs   File: test_utils.py    MIT License 6 votes vote down vote up
def test_meta_has_get_field_method(self):
        class GetFieldModel(models.Model):
            some_field = models.IntegerField()

        class MockField(object):
            def __init__(self, name='test field'):
                self.name = name

        instance = GetFieldModel(some_field=5)
        instance._meta.get_fields = lambda x: x
        instance._meta.get_all_field_names = lambda x: x
        with patch.object(
            instance._meta,
            'get_fields',
            return_value=[MockField('id'), MockField('some_field')]
        ):
            field_names = get_model_field_names(instance)
        self.assertEqual(field_names, ['id', 'some_field']) 
Example 11
Project: liberator   Author: libscie   File: utils.py    Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 12
Project: banruo   Author: yingshang   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # BooleanField needs special-case null-handling, so it comes before the
    # general null test.
    elif isinstance(field, models.BooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 13
Project: kobo-predict   Author: awemulya   File: ScheduleViewset.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def filter_queryset(self, queryset):
        if self.request.user.is_anonymous():
            self.permission_denied(self.request)
        is_project = self.kwargs.get('is_project', None)
        pk = self.kwargs.get('pk', None)
        if is_project == "1":
            queryset = queryset.filter(project__id=pk)
            return queryset.annotate(response_count=Count("schedule_forms__project_form_instances")).select_related('schedule_forms', 'schedule_forms__xf', 'schedule_forms__em')
        else:
            project_id = get_object_or_404(Site, pk=pk).project.id
            queryset = queryset.filter(Q(site__id=pk, schedule_forms__from_project=False)
                                       | Q(project__id=project_id))
            return queryset.annotate(
                site_response_count=Count("schedule_forms__site_form_instances", ),
                response_count=Count(Case(
                    When(project__isnull=False, schedule_forms__project_form_instances__site__id=pk, then=F('schedule_forms__project_form_instances')),
                    output_field=IntegerField(),
                ), distinct=True)

            ).select_related('schedule_forms','schedule_forms__xf', 'schedule_forms__em') 
Example 14
Project: kobo-predict   Author: awemulya   File: FieldSightXformViewset.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def filter_queryset(self, queryset):
        if self.request.user.is_anonymous():
            self.permission_denied(self.request)
        is_project = self.kwargs.get('is_project', None)
        pk = self.kwargs.get('pk', None)
        if is_project == "1":
            queryset = queryset.filter(project__id=pk)
            return queryset.select_related('xf', 'em')
        else:
            project_id = get_object_or_404(Site, pk=pk).project.id
            queryset = queryset.filter(Q(site__id=pk, from_project=False)
                                       | Q (project__id=project_id))
            return queryset.annotate(
                site_response_count=Count("site_form_instances",),
                response_count=Count(Case(
                    When(project__isnull=False, project_form_instances__site__id=pk, then=F('project_form_instances')),
                    output_field=IntegerField(),
                ), distinct=True)

            ).select_related('xf', 'em') 
Example 15
Project: xadmin_bugfix   Author: vip68   File: filters.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 16
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 17
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 18
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 19
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_concrete_class_for_model_field(cls, model_field):
        """
        Method for getting a concrete model class to represent the type of form field required

        :param model_field: Model Field instance
        :return: OmniField subclass
        """
        field_mapping = {
            models.CharField: OmniCharField,
            models.TextField: OmniCharField,
            models.BooleanField: OmniBooleanField,
            models.NullBooleanField: OmniBooleanField,
            models.DateField: OmniDateField,
            models.DateTimeField: OmniDateTimeField,
            models.DecimalField: OmniDecimalField,
            models.EmailField: OmniEmailField,
            models.FloatField: OmniFloatField,
            models.IntegerField: OmniIntegerField,
            models.BigIntegerField: OmniIntegerField,
            models.PositiveIntegerField: OmniIntegerField,
            models.PositiveSmallIntegerField: OmniIntegerField,
            models.SmallIntegerField: OmniIntegerField,
            models.CommaSeparatedIntegerField: OmniCharField,
            models.TimeField: OmniTimeField,
            models.URLField: OmniUrlField,
            models.ForeignKey: OmniForeignKeyField,
            models.ManyToManyField: OmniManyToManyField,
            models.SlugField: OmniSlugField,
            models.FileField: OmniFileField,
            models.ImageField: OmniImageField,
            models.DurationField: OmniDurationField,
            models.GenericIPAddressField: OmniGenericIPAddressField
        }
        field_mapping.update(cls.get_custom_field_mapping())
        return field_mapping.get(model_field.__class__) 
Example 20
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_order_field(self):
        """
        The model should have an order field
        """
        field = OmniField._meta.get_field('order')
        self.assertIsInstance(field, models.IntegerField)
        self.assertEqual(field.default, 0)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 21
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_concrete_class_for_model_field(self):
        """
        The get_concrete_class_for_model_field method should return the correct OmniField subclass
        """
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.CharField()), OmniCharField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.NullBooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DateTimeField()), OmniDateTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DecimalField()), OmniDecimalField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.EmailField()), OmniEmailField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FloatField()), OmniFloatField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.IntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BigIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.PositiveIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SmallIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.TimeField()), OmniTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.URLField()), OmniUrlField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SlugField()), OmniSlugField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FileField()), OmniFileField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.ImageField()), OmniImageField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DurationField()), OmniDurationField)
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.GenericIPAddressField()),
            OmniGenericIPAddressField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.CommaSeparatedIntegerField()),
            OmniCharField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.PositiveSmallIntegerField()),
            OmniIntegerField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ForeignKey(DummyModel2)),
            OmniForeignKeyField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ManyToManyField(DummyModel2)),
            OmniManyToManyField
        ) 
Example 22
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_initial(self):
        """
        The model should have an initial field
        """
        field = OmniIntegerField._meta.get_field('initial_data')
        self.assertIsInstance(field, models.IntegerField)
        self.assertTrue(field.blank)
        self.assertTrue(field.null) 
Example 23
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_min_value(self):
        """
        The model should have a min_value field
        """
        field = OmniIntegerField._meta.get_field('min_value')
        self.assertIsInstance(field, models.IntegerField)
        self.assertTrue(field.blank)
        self.assertTrue(field.null) 
Example 24
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_field_class(self):
        """
        The model should define the correct field class
        """
        self.assertEqual(OmniIntegerField.FIELD_CLASS, 'django.forms.IntegerField') 
Example 25
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_order_field(self):
        """
        The model should have an order field
        """
        field = OmniFormHandler._meta.get_field('order')
        self.assertIsInstance(field, models.IntegerField)
        self.assertEqual(field.default, 0)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 26
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_make_echoicefield(self):
        choice = make_echoicefield(ETestIntChoices, validators=int_validators)
        self.assertTrue(choice.__class__.__bases__[0] is models.IntegerField)
        self.assertIs(choice.get_internal_type(), models.IntegerField.__name__) 
Example 27
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_null_field_factory():
    from django.db import models

    class ShouldBeNullField(models.Field):
        pass

    class FooModel(models.Model):
        should_be_null = ShouldBeNullField()
        foo = models.IntegerField()

    register_field_factory(ShouldBeNullField, None)

    form = Form.from_model(data=None, model=FooModel)
    assert list(form.fields_by_name.keys()) == ['foo'] 
Example 28
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_from_model_subtype():
    from django.db import models

    class Foo(models.IntegerField):
        pass

    class FromModelSubtype(models.Model):
        foo = Foo()

    result = Field.from_model(model=FromModelSubtype, field_name='foo')

    assert result.parse is int_parse 
Example 29
Project: django-river   Author: javrasya   File: classworkflowobject.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_available_approvals(self, as_user):
        those_with_max_priority = With(
            TransitionApproval.objects.filter(
                workflow=self.workflow, status=PENDING
            ).values(
                'workflow', 'object_id', 'transition'
            ).annotate(min_priority=Min('priority'))
        )

        workflow_objects = With(
            self.wokflow_object_class.objects.all(),
            name="workflow_object"
        )

        approvals_with_max_priority = those_with_max_priority.join(
            self._authorized_approvals(as_user),
            workflow_id=those_with_max_priority.col.workflow_id,
            object_id=those_with_max_priority.col.object_id,
            transition_id=those_with_max_priority.col.transition_id,
        ).with_cte(
            those_with_max_priority
        ).annotate(
            object_id_as_int=Cast('object_id', IntegerField()),
            min_priority=those_with_max_priority.col.min_priority
        ).filter(min_priority=F("priority"))

        return workflow_objects.join(
            approvals_with_max_priority, object_id_as_int=workflow_objects.col.pk
        ).with_cte(
            workflow_objects
        ).filter(transition__source_state=getattr(workflow_objects.col, self.field_name + "_id")) 
Example 30
Project: chattR   Author: patrickstocklin   File: functions.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', IntegerField())
        super(Length, self).__init__(expression, output_field=output_field, **extra) 
Example 31
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def db_type(self, connection):
        # The database column type of a ForeignKey is the column type
        # of the field to which it points. An exception is if the ForeignKey
        # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
        # in which case the column type is simply that of an IntegerField.
        # If the database needs similar types for key fields however, the only
        # thing we can do is making AutoField an IntegerField.
        rel_field = self.related_field
        if (isinstance(rel_field, AutoField) or
                (not connection.features.related_fields_match_type and
                isinstance(rel_field, (PositiveIntegerField,
                                       PositiveSmallIntegerField)))):
            return IntegerField().db_type(connection=connection)
        return rel_field.db_type(connection=connection) 
Example 32
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 33
Project: opadmin   Author: cc0411   File: filters.py    GNU General Public License v3.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 34
Project: StormOnline   Author: stormsha   File: filters.py    Apache License 2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 35
Project: litmus-site   Author: alps-jbnu   File: ranked_submission.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        if self.in_contest:
            contest_join = '''INNER JOIN judge_contestsubmission AS cs ON (sub.id = cs.submission_id)
                              INNER JOIN judge_contestparticipation AS cp ON (cs.participation_id = cp.id)'''
            points = 'cs.points'
            constraint = 'AND cp.contest_id = %s'
        else:
            contest_join = ''
            points = 'sub.points'
            constraint = ''
        queryset = super(RankedSubmissions, self).get_queryset().filter(id__in=RawSQL(
                '''
                    SELECT sub.id
                    FROM (
                        SELECT sub.user_id AS uid, MAX(sub.points) AS points
                        FROM judge_submission AS sub INNER JOIN
                             judge_problem AS prob ON (sub.problem_id = prob.id) {contest_join}
                        WHERE sub.problem_id = %s AND {points} > 0 {constraint}
                        GROUP BY sub.user_id
                    ) AS highscore INNER JOIN (
                        SELECT sub.user_id AS uid, sub.points, MIN(sub.time) as time
                        FROM judge_submission AS sub INNER JOIN
                             judge_problem AS prob ON (sub.problem_id = prob.id) {contest_join}
                        WHERE sub.problem_id = %s AND {points} > 0 {constraint}
                        GROUP BY sub.user_id, {points}
                    ) AS fastest ON (highscore.uid = fastest.uid AND highscore.points = fastest.points)
                        INNER JOIN judge_submission AS sub
                            ON (sub.user_id = fastest.uid AND sub.time = fastest.time) {contest_join}
                    WHERE sub.problem_id = %s AND {points} > 0 {constraint}
                    GROUP BY fastest.uid
                '''.format(points=points, contest_join=contest_join, constraint=constraint),
                (self.problem.id, self.contest.id) * 3 if self.in_contest else (self.problem.id,) * 3,
                output_field=IntegerField()))
        queryset.query.group_by = ['user_id']

        if self.in_contest:
            return queryset.order_by('-contest__points', 'time')
        else:
            return queryset.order_by('-points', 'time') 
Example 36
Project: resolwe   Author: genialis   File: viewsets.py    Apache License 2.0 5 votes vote down vote up
def list_with_post(self, request):
        """Endpoint handler."""
        if self.is_search_request():
            search = self.search()

            page = self.paginate_queryset(search)
            if page is None:
                items = search
            else:
                items = page

            try:
                primary_keys = []
                order_map_cases = []
                for order, item in enumerate(items):
                    pk = item[self.primary_key_field]
                    primary_keys.append(pk)
                    order_map_cases.append(When(pk=pk, then=Value(order)))

                queryset = self.get_queryset().filter(
                    pk__in=primary_keys
                ).order_by(
                    Case(*order_map_cases, output_field=IntegerField()).asc()
                )
            except KeyError:
                raise KeyError("Combined viewset requires that your index contains a field with "
                               "the primary key. By default this field is called 'id', but you "
                               "can change it by setting primary_key_field.")

            # Pagination must be handled differently.
            serializer = self.get_serializer(queryset, many=True)
            if page is not None:
                return self.get_paginated_response(serializer.data)

            return Response(serializer.data)
        else:
            queryset = self.filter_queryset(self.get_queryset())
            return self.paginate_response(queryset) 
Example 37
Project: django-idcops   Author: Wenvki   File: utils.py    Apache License 2.0 5 votes vote down vote up
def display_for_field(value, field, html=True, only_date=True):
    if getattr(field, 'flatchoices', None):
        if html and field.name == 'color' and value:
            return make_color_icon(value)
        return dict(field.flatchoices).get(value, '')
    elif html and (isinstance(field, (models.BooleanField, models.NullBooleanField))):
        return make_boolean_icon(value)
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        boolchoice = {False: "否", True: "是"}
        return boolchoice.get(value)
    elif value is None:
        return ""
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.ForeignKey) and value:
        rel_obj = field.related_model.objects.get(pk=value)
        if html and COLOR_FK_FIELD and isinstance(rel_obj, Option):
            text_color = rel_obj.color
            if not text_color:
                text_color = 'text-info'
            safe_value = format_html(
                '<span class="text-{}">{}</span>', text_color, rel_obj.text)
            return safe_value
        return force_text(rel_obj)
    elif isinstance(field, models.TextField) and value:
        return force_text(value)
    elif isinstance(field, models.DateTimeField):
        if only_date:
            return formats.date_format(value)
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value) 
Example 38
Project: tapedrive   Author: janw   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(
        self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs
    ):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs) 
Example 39
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def db_type(self, connection):
        # The database column type of a ForeignKey is the column type
        # of the field to which it points. An exception is if the ForeignKey
        # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
        # in which case the column type is simply that of an IntegerField.
        # If the database needs similar types for key fields however, the only
        # thing we can do is making AutoField an IntegerField.
        rel_field = self.related_field
        if (isinstance(rel_field, AutoField) or
                (not connection.features.related_fields_match_type and
                isinstance(rel_field, (PositiveIntegerField,
                                       PositiveSmallIntegerField)))):
            return IntegerField().db_type(connection=connection)
        return rel_field.db_type(connection=connection) 
Example 40
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 5 votes vote down vote up
def test_signal_handler_raises_error_on_incorrect_field(self):
        class BadFieldModel(models.Model):
            some_field = models.IntegerField()

            @cleans_field('tests.BadFieldModel.not_a_field')
            def clean_some_field(self, some_field):
                return some_field + 1

        dummy = BadFieldModel(some_field=5)
        with self.assertRaises(CleanFieldsConfigurationError) as ctx:
            pre_save.send(dummy.__class__, instance=dummy)
        self.assertIn('tests.BadFieldModel', str(ctx.exception))
        self.assertIn('not_a_field', str(ctx.exception))
        self.assertIn('clean_some_field', str(ctx.exception)) 
Example 41
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 5 votes vote down vote up
def test_signal_handler_raises_error_on_incorrect_field(self):
        class BadFieldContextModel(models.Model):
            some_field = models.IntegerField()

            @cleans_field_with_context('tests.BadFieldContextModel.no_field')
            def clean_some_field(self, some_field, data):
                return some_field + 1

        dummy = BadFieldContextModel(some_field=5)
        with self.assertRaises(CleanFieldsConfigurationError) as ctx:
            pre_save.send(dummy.__class__, instance=dummy)
        self.assertIn('tests.BadFieldContextModel', str(ctx.exception))
        self.assertIn('no_field', str(ctx.exception))
        self.assertIn('clean_some_field', str(ctx.exception)) 
Example 42
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 5 votes vote down vote up
def test_instance_method_cleaner(self):
        class InstanceMethodModel(models.Model):
            some_field = models.IntegerField()

            def clean_some_field(self, some_field):
                return some_field + 1

        dummy = InstanceMethodModel(some_field=5)
        value = call_cleaner(dummy.clean_some_field, [dummy.some_field], dummy)
        self.assertEqual(value, 6) 
Example 43
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 5 votes vote down vote up
def test_wrapped_instance_method_cleaner_raises_type_error(self):
        class ErrorRaisingWrappedMethodModel(models.Model):
            some_field = models.IntegerField()

            def clean_some_field(self, some_field):
                raise TypeError('this is a legitimate error')

        dummy = ErrorRaisingWrappedMethodModel(some_field=5)
        wrapped_cleaner = dummy_wrapper(dummy.clean_some_field)
        with self.assertRaises(TypeError) as ctx:
            call_cleaner(wrapped_cleaner, [dummy.some_field], dummy)
        self.assertEqual(str(ctx.exception), 'this is a legitimate error') 
Example 44
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 5 votes vote down vote up
def test_function_cleaner(self):
        class FunctionCleanerModel(models.Model):
            some_field = models.IntegerField()

        def clean_some_field(some_field):
            return some_field + 1

        dummy = FunctionCleanerModel(some_field=5)
        value = call_cleaner(clean_some_field, [dummy.some_field], dummy)
        self.assertEqual(value, 6) 
Example 45
Project: django-clean-fields   Author: lamarmeigs   File: test_decorators.py    MIT License 5 votes vote down vote up
def test_cleaner_raises_type_error(self):
        class RaiseErrorCleanerModel(models.Model):
            field_1 = models.IntegerField()
            field_2 = models.IntegerField()
            field_3 = models.IntegerField()
            field_4 = models.IntegerField()

            @cleans_field('tests.RaiseErrorCleanerModel.field_1')
            @cleans_field('tests.RaiseErrorCleanerModel.field_2')
            def clean_some_field(self, some_field):
                if isinstance(some_field, int):
                    return some_field
                raise TypeError('some_field is the wrong type')

            @cleans_field_with_context('tests.RaiseErrorCleanerModel.field_3')
            @cleans_field_with_context('tests.RaiseErrorCleanerModel.field_4')
            def clean_other_fields(self, other_field, data):
                if isinstance(other_field, int):
                    return other_field
                raise TypeError('other_field is the wrong type')

        dummy = RaiseErrorCleanerModel(
            field_1=5, field_2='str', field_3=4, field_4=4
        )
        with self.assertRaises(TypeError) as ctx:
            pre_save.send(dummy.__class__, instance=dummy)
        self.assertEqual(str(ctx.exception), 'some_field is the wrong type')

        dummy = RaiseErrorCleanerModel(
            field_1=1, field_2=2, field_3='str', field_4=4
        )
        with self.assertRaises(TypeError) as ctx:
            pre_save.send(dummy.__class__, instance=dummy)
        self.assertEqual(str(ctx.exception), 'other_field is the wrong type') 
Example 46
Project: django-clean-fields   Author: lamarmeigs   File: test_models.py    MIT License 5 votes vote down vote up
def test_save_invokes_clean_single_fields(self, mock_save):
        class SaveableBaseModel(BaseCleanFieldsModel):
            some_field = models.IntegerField()

        dummy = SaveableBaseModel(some_field=5)
        with patch.object(dummy, 'clean_single_fields') as mock_clean_fields:
            dummy.save()
        mock_clean_fields.assert_called_once_with()
        mock_save.assert_called_once_with() 
Example 47
Project: django-clean-fields   Author: lamarmeigs   File: test_models.py    MIT License 5 votes vote down vote up
def test_clean_single_fields_without_cleaner(self):
        class CleanerlessBaseModel(BaseCleanFieldsModel):
            some_field = models.IntegerField()

        dummy = CleanerlessBaseModel(some_field=5)
        with patch.object(dummy, '_get_field_cleaner', return_value=None):
            dummy.clean_single_fields()
        self.assertEqual(dummy.some_field, 5) 
Example 48
Project: django-clean-fields   Author: lamarmeigs   File: test_models.py    MIT License 5 votes vote down vote up
def test_clean_single_fields_with_cleaner(self):
        class CleaningBaseModel(BaseCleanFieldsModel):
            some_field = models.IntegerField()

        dummy = CleaningBaseModel(some_field=5)
        with patch.object(
            dummy,
            '_get_field_cleaner',
            return_value=lambda: 42
        ):
            dummy.clean_single_fields()
        self.assertEqual(dummy.some_field, 42) 
Example 49
Project: django-clean-fields   Author: lamarmeigs   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_find_cleaner_with_uncallable_cleaner(self):
        class UncallableCleanerNaiveModel(CleanFieldsModel):
            some_field = models.IntegerField()
            clean_some_field = 'not callable'

        dummy = UncallableCleanerNaiveModel(some_field=5)
        self.assertIsNone(dummy._get_field_cleaner('some_field')) 
Example 50
Project: django-clean-fields   Author: lamarmeigs   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_find_cleaner_returns_cleaner(self):
        class CleaningNaiveModel(CleanFieldsModel):
            some_field = models.IntegerField()

            def clean_some_field(self):
                return 42

        dummy = CleaningNaiveModel(some_field=5)
        self.assertEqual(
            dummy._get_field_cleaner('some_field'),
            dummy.clean_some_field
        ) 
Example 51
Project: django-clean-fields   Author: lamarmeigs   File: test_utils.py    MIT License 5 votes vote down vote up
def test_model_has_no_field(self):
        class MissingFieldModel(models.Model):
            some_field = models.IntegerField()

        dummy = MissingFieldModel(some_field=5)
        with self.assertRaises(AttributeError) as ctx:
            get_model_field_value(dummy, 'not_a_field')
        self.assertEqual(
            str(ctx.exception),
            'Object {} has no field named "not_a_field"'.format(dummy)
        ) 
Example 52
Project: django-clean-fields   Author: lamarmeigs   File: test_utils.py    MIT License 5 votes vote down vote up
def test_model_has_field(self):
        class HasFieldModel(models.Model):
            some_field = models.IntegerField()

        dummy = HasFieldModel(some_field=5)
        field_value = get_model_field_value(dummy, 'some_field')
        self.assertEqual(field_value, 5) 
Example 53
Project: cosinnus-core   Author: wechange-eg   File: idea.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def annotate_likes(self):
        """ Annotates the number of likes as `like_count` """
        ann = self.annotate(
                like_count=models.Count(
                    models.Case(
                        models.When(likes__liked=True, then=1),
                            default=0, output_field=models.IntegerField()
                    )
                )
            )
        return ann 
Example 54
Project: GTDWeb   Author: lanbing510   File: functions.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', IntegerField())
        super(Length, self).__init__(expression, output_field=output_field, **extra) 
Example 55
Project: GTDWeb   Author: lanbing510   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def db_type(self, connection):
        # The database column type of a ForeignKey is the column type
        # of the field to which it points. An exception is if the ForeignKey
        # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
        # in which case the column type is simply that of an IntegerField.
        # If the database needs similar types for key fields however, the only
        # thing we can do is making AutoField an IntegerField.
        rel_field = self.related_field
        if (isinstance(rel_field, AutoField) or
                (not connection.features.related_fields_match_type and
                isinstance(rel_field, (PositiveIntegerField,
                                       PositiveSmallIntegerField)))):
            return IntegerField().db_type(connection=connection)
        return rel_field.db_type(connection=connection) 
Example 56
Project: GTDWeb   Author: lanbing510   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 57
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_description(self):
        field = encrypt(models.IntegerField())
        self.assertEqual('Encrypted Integer', field.description) 
Example 58
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_clone(self):
        field = encrypt(models.IntegerField())
        new_field = field.clone()
        self.assertIsNot(field, new_field)
        self.assertEqual(field.verbose_name, new_field.verbose_name)
        self.assertNotEqual(field.creation_counter, new_field.creation_counter) 
Example 59
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct(self):
        field = encrypt(models.IntegerField())
        name, path, args, kwargs = field.deconstruct()
        new = encrypt(*args, **kwargs)
        self.assertEqual(type(new), type(field)) 
Example 60
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct_with_ttl(self):
        field = encrypt(models.IntegerField(), ttl=60)
        name, path, args, kwargs = field.deconstruct()
        new = encrypt(*args, **kwargs)
        self.assertEqual(new.ttl, field.ttl) 
Example 61
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subclass_deconstruct(self):
        field = encrypt(models.IntegerField())
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual('django_cryptography.fields.encrypt', path)

        field = EncryptedFieldSubclass()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual('tests.fields.models.EncryptedFieldSubclass', path) 
Example 62
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_blank_true(self):
        field = encrypt(models.IntegerField(blank=True, null=True))
        # This should not raise a validation error
        field.clean(None, None) 
Example 63
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_with_validators(self):
        field = encrypt(
            models.IntegerField(validators=[validators.MinValueValidator(1)]))
        field.clean(1, None)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(0, None)
        self.assertEqual('Ensure this value is greater than or equal to 1.',
                         cm.exception.messages[0]) 
Example 64
Project: pik-django-utils   Author: pik-software   File: versioned.py    MIT License 5 votes vote down vote up
def optimistic_concurrency_update(self, **kwargs):
        """
        Safe optimistic concurrent update. If the object was not modified
        since we fetched it than the object is updated and function will
        return `True`. If it was modified than the function will
        return `False` and the object will not be updated.

        NOTE 1: In an environment with a lot of concurrent updates
        this approach might be wasteful.

        NOTE 2: This approach does not protect from modifications made
        to the object outside this function. If you have other tasks
        that modify the data directly (e.g use `save()` directly)
        you need to make sure they use the version as well.

        Example:

            class Account(Versioned):
                balance = models.IntegerField(default=100)

                def withdraw(self, amount):
                    if self.balance < amount:
                        raise errors.RuntimeError()

                    result = self.balance - amount
                    return self.optimistic_concurrency_update(balance=balance)

            x = Account()
            x.withdraw(100)
            x.withdraw(100)

        :return: is the object updated
        :rtype: bool
        """
        # more detail here: https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2  # noqa
        kwargs['version'] = self.version + 1
        model = type(self)
        updated = model.objects.filter(pk=self.pk, version=self.version) \
            .update(**kwargs)
        # TODO: trigger post_save event
        return updated > 0 
Example 65
Project: liberator   Author: libscie   File: statistics.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def __init__(self, y, x):
        super(RegrCount, self).__init__(y=y, x=x, output_field=IntegerField()) 
Example 66
Project: aswan   Author: momosecurity   File: models.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_hit_log_model(db_table):
    class CustomMetaClass(ModelBase):
        def __new__(cls, name, bases, attrs):
            model = super(CustomMetaClass, cls).__new__(cls, name, bases,
                                                        attrs)
            model._meta.db_table = db_table
            model._meta.index_together = (
                ('time',),
                ('user_id',),
            )
            model.managed = False
            return model

    class HitLogModel(models.Model, metaclass=CustomMetaClass):
        time = models.DateTimeField(verbose_name=_(u'命中时间'))
        rule_id = models.IntegerField(verbose_name=_(u'规则ID'))
        user_id = models.IntegerField(verbose_name=_(u'命中用户'))
        kwargs = models.CharField(max_length=128, null=False, default='', verbose_name=_(u'扩展参数'))
        req_body = models.CharField(max_length=512, null=False, default='', verbose_name=_(u'请求参数'))
        control = models.CharField(max_length=16, null=False, default='', verbose_name=_(u'管控原子'))
        custom = models.CharField(max_length=50, null=False, default='', verbose_name=_(u'策略组解释'))
        group_name = models.CharField(max_length=256, null=False, default='',
                                      verbose_name=_(u'策略原子组名称'))
        group_uuid = models.CharField(max_length=36, null=False, default='',
                                      verbose_name=_(u'策略原子组UUID'))
        hit_number = models.PositiveSmallIntegerField(null=False, default=1, verbose_name=_(u'命中次序'))

        objects = Manager()

    return HitLogModel 
Example 67
Project: safe-relay-service   Author: gnosis   File: models.py    MIT License 5 votes vote down vote up
def get_tokens_usage(self) -> Optional[List[Dict[str, Any]]]:
        """
        :return: List of Dict 'gas_token', 'total', 'number', 'percentage'
        """
        total = self.deployed_and_checked().annotate(_x=Value(1)).values('_x').annotate(total=Count('_x')
                                                                                        ).values('total')
        return self.deployed_and_checked().values('payment_token').annotate(
            total=Subquery(total, output_field=models.IntegerField())
        ).annotate(
            number=Count('safe_id'), percentage=Cast(100.0 * Count('pk') / F('total'),
                                                     models.FloatField())) 
Example 68
Project: safe-relay-service   Author: gnosis   File: models.py    MIT License 5 votes vote down vote up
def get_tokens_usage(self) -> Optional[List[Dict[str, Any]]]:
        """
        :return: List of Dict 'gas_token', 'total', 'number', 'percentage'
        """
        total = self.annotate(_x=Value(1)).values('_x').annotate(total=Count('_x')).values('total')
        return self.values(
            'gas_token'
        ).annotate(
            total=Subquery(total, output_field=models.IntegerField())
        ).annotate(
            number=Count('pk'), percentage=Cast(100.0 * Count('pk') / F('total'), models.FloatField())
        ) 
Example 69
Project: kobo-predict   Author: awemulya   File: fieldsight_models.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs) 
Example 70
Project: kobo-predict   Author: awemulya   File: bar_data_project.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project):
        self.data = OrderedDict()
        
        
        data = Site.objects.filter(project_id = project.id).aggregate(
             unstarted = Sum(
                 Case(When(current_progress = 0, then= 1),
                      output_field = IntegerField())
             ),
             first = Sum(
                 Case(When(current_progress__gte = 1, current_progress__lt = 20, then= 1),
                      output_field = IntegerField())
             ),
             second = Sum(
                 Case(When(current_progress__gte = 20, current_progress__lt= 40, then= 1),
                      output_field = IntegerField())
             ),
             third = Sum(
                 Case(When(current_progress__gte = 40, current_progress__lt= 60, then= 1),
                      output_field = IntegerField())
             ),
             fourth = Sum(
                 Case(When(current_progress__gte = 60, current_progress__lt= 80, then= 1),
                      output_field = IntegerField())
             ),
             fifth = Sum(
                 Case(When(current_progress__gte = 80, current_progress__lt= 100, then= 1),
                      output_field = IntegerField())
             ),
            sixth = Sum(
                 Case(When(current_progress = 100, then = 1),
                      output_field = IntegerField())
             )
        )
        self.data['Unstarted'] = 0 if data['unstarted'] is None else data['unstarted']
        self.data['< 20'] = 0 if data['first'] is None else data['first']
        self.data['20 - 40'] = 0 if data['second'] is None else data['second']
        self.data['40 - 60'] = 0 if data['third'] is None else data['third']
        self.data['60 - 80'] = 0 if data['fourth'] is None else data['fourth']
        self.data['80 <'] = 0 if data['fifth'] is None else data['fifth']
        self.data['Completed'] = 0 if data['sixth'] is None else data['sixth'] 
Example 71
Project: kobo-predict   Author: awemulya   File: models.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_submissions_count(self):
        qs = self.project_instances.aggregate(
            outstanding=Count(Case(When(form_status=0, project=self, then=1), output_field=IntegerField(),)),
            flagged=Count(Case(When(form_status=2, project=self, then=1), output_field=IntegerField(),)),
            approved=Count(Case(When(form_status=3, project=self, then=1), output_field=IntegerField(),)),
            rejected=Count(Case(When(form_status=1, project=self, then=1), output_field=IntegerField(),)),
        )
        return qs.get('outstanding', 0), qs.get('flagged', 0), qs.get('approved', 0), qs.get('rejected', 0) 
Example 72
Project: ops22   Author: spark8103   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example 73
Project: django-echoices   Author: mbourqui   File: fields.py    GNU General Public License v3.0 4 votes vote down vote up
def make_echoicefield(echoices, *args, klass_name=None, **kwargs):
    """
    Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values.

    Parameters
    ----------
    echoices : subclass of EChoice
    args
        Passed to the derived `models.Field`
    klass_name : str
        Give a specific name to the returned class.
        By default for Django < 1.9, the name will be 'EChoiceField'.
        By default for Django >= 1.9, the name will be the name of the enum appended with 'Field'.
    kwargs
        Passed to the derived `models.Field`

    Returns
    -------
    EChoiceField
        For Django>=1.9, the exact name of the returned Field is based on the name of the `echoices` with a suffixed
        'Field'. For older Django, the returned name of the class is `EChoiceField`.

    """
    assert issubclass(echoices, EChoice)
    value_type = echoices.__getvaluetype__()
    if value_type is str:
        cls_ = models.CharField
    elif value_type is int:
        cls_ = models.IntegerField
    elif value_type is float:
        cls_ = models.FloatField
    elif value_type is bool:
        cls_ = models.BooleanField
    else:
        raise NotImplementedError("Please open an issue if you wish your value type to be supported: "
                                  "https://github.com/mbourqui/django-echoices/issues/new")
    if klass_name and StrictVersion(django_version()) < StrictVersion('1.9.0'):
        warnings.warn("Django < 1.9 throws an 'ImportError' if the class name is not defined in the module. "
                      "The provided klass_name will be replaced by {}".format(EChoiceField.__name__), RuntimeWarning)
    klass_name = EChoiceField.__name__ if StrictVersion(django_version()) < StrictVersion('1.9.0') else \
        klass_name if klass_name else "{}Field".format(echoices.__name__)
    d = dict(cls_.__dict__)
    d.update(dict(EChoiceField.__dict__))
    return type(klass_name, (cls_,), d)(echoices, *args, **kwargs)

# TODO: MultipleEChoiceField 
Example 74
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_get_name_field():
    from django.db.models import (
        Model,
        IntegerField,
        CharField,
        ForeignKey,
        CASCADE,
    )

    class Foo1(Model):
        a = IntegerField()
        name = CharField(max_length=255)

    class Bar1(Model):
        foo = ForeignKey(Foo1, on_delete=CASCADE)

    class Foo2(Model):
        a = IntegerField()
        fooname = CharField(max_length=255)
        name = CharField(max_length=255)

    class Bar2(Model):
        foo = ForeignKey(Foo2, on_delete=CASCADE)

    class Foo3(Model):
        name = IntegerField()
        fooname = CharField(max_length=255)

    class Bar3(Model):
        foo = ForeignKey(Foo3, on_delete=CASCADE)

    class Foo4(Model):
        fooname = CharField(max_length=255)
        barname = CharField(max_length=255)

    class Bar4(Model):
        foo = ForeignKey(Foo4, on_delete=CASCADE)

    class Foo5(Model):
        blabla = CharField(max_length=255)

    class Bar5(Model):
        foo = ForeignKey(Foo5, on_delete=CASCADE)

    class Foo6(Model):
        a = IntegerField()

    class Bar6(Model):
        foo = ForeignKey(Foo6, on_delete=CASCADE)

    assert get_name_field(Form.from_model(model=Bar1, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar2, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar3, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar4, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar5, data={}).fields_by_name.foo) == 'blabla'
    with pytest.raises(AssertionError):
        get_name_field(Form.from_model(model=Bar6, data={}).fields_by_name.foo) 
Example 75
Project: openhatch   Author: campbe13   File: 0002_milestone_b_data.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        try:
            # Adding field 'Bug.submitter_realname'
            db.add_column('search_bug', 'submitter_realname', models.CharField(max_length=200))
        except:
            pass

        try:
             # Adding field 'Project.icon_url'
            db.add_column('search_project', 'icon_url', models.URLField(max_length=200))
        except:
            pass
        
        try:
            # Adding field 'Bug.last_touched'
            db.add_column('search_bug', 'last_touched', models.DateField(default=datetime.datetime(1970, 1, 1, 12, 0, 0)))
        except:
            pass
        
        try:
            # Adding field 'Bug.importance'
            db.add_column('search_bug', 'importance', models.CharField(max_length=200))
        except:
            pass
        
        try:
            # Adding field 'Bug.people_involved'
            db.add_column('search_bug', 'people_involved', models.IntegerField(default=0))
        except:
            pass
        
        try:
            # Adding field 'Bug.last_polled'
            db.add_column('search_bug', 'last_polled', models.DateField(default=datetime.datetime(1970, 1, 1, 12, 0, 0)))
        except:
            pass
        
        try:
            # Adding field 'Bug.submitter_username'
            db.add_column('search_bug', 'submitter_username', models.CharField(max_length=200))
        except:
            pass 
Example 76
Project: chattR   Author: patrickstocklin   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 77
Project: TESTGIT   Author: B-ROY   File: layermapping.py    Apache License 2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
            isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if model_field.max_length and len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2] # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 78
Project: AneMo   Author: jspargo   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if model_field.max_length and len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 79
Project: GTDWeb   Author: lanbing510   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 80
Project: liberator   Author: libscie   File: layermapping.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val