Python django.db.models.IntegerField() Examples

The following are 30 code examples of django.db.models.IntegerField(). 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 , or try the search function .
Example #1
Source File: ScheduleViewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 8 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 #2
Source File: views.py    From timed-backend with GNU Affero General Public License v3.0 8 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self._extract_user()

        queryset = models.AbsenceType.objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        queryset = queryset.annotate(user=Value(user.id, IntegerField()))
        queryset = queryset.annotate(
            pk=Concat(
                "user", Value("_"), "id", Value("_"), "date", output_field=CharField()
            )
        )

        # only myself, superuser and supervisors may see by absence balances
        current_user = self.request.user

        if not current_user.is_superuser:
            if current_user.id != user.id:
                if not current_user.supervisees.filter(id=user.id).exists():
                    return models.AbsenceType.objects.none()

        return queryset 
Example #3
Source File: models.py    From django-closuretree with Apache License 2.0 6 votes vote down vote up
def create_closure_model(cls):
    """Creates a <Model>Closure model in the same module as the model."""
    meta_vals = {
        'unique_together':  (("parent", "child"),)
    }
    if getattr(cls._meta, 'db_table', None):
        meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table')
    model = type('%sClosure' % cls.__name__, (models.Model,), {
        'parent': models.ForeignKey(
            cls.__name__,
            related_name=cls.closure_parentref()
        ),
        'child': models.ForeignKey(
            cls.__name__,
            related_name=cls.closure_childref()
        ),
        'depth': models.IntegerField(),
        '__module__':   cls.__module__,
        '__unicode__': _closure_model_unicode,
        'Meta': type('Meta', (object,), meta_vals),
    })
    setattr(cls, "_closure_model", model)
    return model 
Example #4
Source File: utils.py    From openhgsenti with Apache License 2.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 field.flatchoices:
        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 smart_text(value) 
Example #5
Source File: FieldSightXformViewset.py    From kobo-predict with 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 #6
Source File: views.py    From pythonic-news with GNU Affero General Public License v3.0 6 votes vote down vote up
def threads(request):
    page = int(request.GET.get('p', 0))
    paging_size = settings.PAGING_SIZE
    tree = Comment.objects.filter( tree_id=OuterRef('tree_id'), user=OuterRef('user')).values('tree_id', 'user__pk').annotate(min_level=Min('level')).order_by()
    stories = Comment.objects.filter(
        user=request.user
    ).filter(
        Q(level__in=Subquery(tree.values('min_level'), output_field=models.IntegerField()))  # TODO: level= or level__in= ???
    ).select_related(
        'user', 'parent', 'to_story'
    ).order_by(
        '-created_at'
    )[(page*paging_size):(page+1)*(paging_size)]
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': None, 'show_children': True}) 
Example #7
Source File: utils.py    From bioforum with MIT License 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, 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 #8
Source File: utils.py    From python with Apache License 2.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)
    # 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 #9
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with MIT License 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 #10
Source File: work_merge.py    From mangaki with GNU Affero General Public License v3.0 6 votes vote down vote up
def redirect_staff(self):
        target_work_staff = set()
        kept_staff_ids = []
        # Only one query: put self.target_work's Staff objects first in the list
        queryset = (Staff.objects.filter(work__in=self.works_to_merge)
            .annotate(belongs_to_target_work=Case(
                When(work_id=self.target_work.id, then=Value(1)),
                     default=Value(0), output_field=IntegerField()))
            .order_by('-belongs_to_target_work')
            .values_list('id', 'work_id', 'artist_id', 'role_id'))
        for staff_id, work_id, artist_id, role_id in queryset:
            if work_id == self.target_work.id:  # This condition will be met for the first iterations
                target_work_staff.add((artist_id, role_id))
            # Now we are sure we know every staff of the final work
            elif (artist_id, role_id) not in target_work_staff:
                kept_staff_ids.append(staff_id)
        Staff.objects.filter(work__in=self.works_to_merge).exclude(work_id=self.target_work.id).exclude(
            id__in=kept_staff_ids).delete()
        Staff.objects.filter(id__in=kept_staff_ids).update(work_id=self.target_work.id) 
Example #11
Source File: models.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(cls, as_dataframe: bool = True, **filter_kwargs):
        """
        Return grouped by method/name statistic with AVG time and N calls
        :param as_dataframe: bool - whether return pandas.dataframe or plain QuerySet
        :param filter_kwargs: positional arguments represents options for filter() qs method
        :return: pandas Dataframe OR QuerySet
        """
        # .filter(has_error=False)\
        qs = cls.objects\
            .values('method', 'path', 'name')\
            .annotate(calls=Count('id'),
                      errors=Count(Case(
                          When(has_error=True, then=1),
                          output_field=IntegerField(),
                      )),
                      avg_time=Avg('time'), max_time=Max('time'))\
            .filter(**filter_kwargs)
        qs = list(qs)
        qs.sort(key=lambda m: -m['calls'])
        if as_dataframe:
            return pd.DataFrame.from_records(qs, columns=['name', 'method',
                                                          'calls', 'errors',
                                                          'avg_time', 'max_time'])
        return qs 
Example #12
Source File: utils_queue.py    From SMART with MIT License 6 votes vote down vote up
def get_queue_size_params(queue, queue_size, num_in_queue, batch_size, irr_queue):
    '''
    Get the sql parameters for the number of items to add to the queue
    '''
    # if there is less space in the queue than the default number of
    # elements to add, or we are trying to fill the queue to the top
    # (irr_queue=None in the second case)
    if (queue_size - num_in_queue < batch_size) or not(irr_queue):
        sample_size_sql, sample_size_params = (Queue.objects.filter(pk=queue.pk)
                                               .annotate(sample_size=F('length') - Count('data'))
                                               .values('sample_size')
                                               .query.sql_with_params())
    else:
        # just add the number requested (some percent of the batch size)
        sample_size_sql, sample_size_params = (Queue.objects.filter(pk=queue.pk)
                                               .annotate(sample_size=Value(batch_size, IntegerField()))
                                               .values('sample_size')
                                               .query.sql_with_params())
    return sample_size_sql, sample_size_params 
Example #13
Source File: sets.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check(self, **kwargs):
        errors = super().check(**kwargs)
        if not isinstance(self.base_field, (CharField, IntegerField)):
            errors.append(
                checks.Error(
                    "Base field for set must be a CharField or IntegerField.",
                    hint=None,
                    obj=self,
                    id="django_mysql.E002",
                )
            )
            return errors

        # Remove the field name checks as they are not needed here.
        base_errors = self.base_field.check()
        if base_errors:
            messages = "\n    ".join(
                "{} ({})".format(error.msg, error.id) for error in base_errors
            )
            errors.append(
                checks.Error(
                    "Base field for set has errors:\n    %s" % messages,
                    hint=None,
                    obj=self,
                    id="django_mysql.E001",
                )
            )
        return errors 
Example #14
Source File: test_listtextfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subclass_deconstruct(self):
        field = ListTextFieldSubclass(models.IntegerField())
        name, path, args, kwargs = field.deconstruct()
        assert path == "tests.testapp.test_listtextfield.ListTextFieldSubclass" 
Example #15
Source File: test_listcharfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct_with_size(self):
        field = ListCharField(models.IntegerField(), size=3, max_length=32)
        name, path, args, kwargs = field.deconstruct()
        new = ListCharField(*args, **kwargs)
        assert new.size == field.size 
Example #16
Source File: test_listtextfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct(self):
        field = ListTextField(models.IntegerField(), max_length=32)
        name, path, args, kwargs = field.deconstruct()
        new = ListTextField(*args, **kwargs)
        assert new.base_field.__class__ == field.base_field.__class__ 
Example #17
Source File: test_listcharfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_int(self):
        field = ListCharField(models.IntegerField(), max_length=32)
        assert field.description == "List of Integer" 
Example #18
Source File: schema.py    From djangoql with MIT License 5 votes vote down vote up
def get_field_cls(self, field):
        str_fields = (models.CharField, models.TextField, models.UUIDField)
        if isinstance(field, str_fields):
            return StrField
        elif isinstance(field, (models.AutoField, models.IntegerField)):
            return IntField
        elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return BoolField
        elif isinstance(field, (models.DecimalField, models.FloatField)):
            return FloatField
        elif isinstance(field, models.DateTimeField):
            return DateTimeField
        elif isinstance(field, models.DateField):
            return DateField
        return DjangoQLField 
Example #19
Source File: test_listcharfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_model_field_formfield_size(self):
        model_field = ListCharField(models.IntegerField(), size=4)
        form_field = model_field.formfield()
        assert isinstance(form_field, SimpleListField)
        assert form_field.max_length == 4 
Example #20
Source File: test_listtextfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bad_import2_deconstruct(self):
        from django_mysql.models.fields.lists import ListTextField as LTField

        field = LTField(models.IntegerField())
        name, path, args, kwargs = field.deconstruct()
        assert path == "django_mysql.models.ListTextField" 
Example #21
Source File: fields.py    From janeway with GNU Affero General Public License v3.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 #22
Source File: crudlfap.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        update = MRSRequestLogEntry.ACTION_UPDATE
        return super().get_queryset().annotate(
            count_updates=Count(Case(
                When(
                    mrsrequestlogentry__action=update,
                    then=1
                ),
                output_field=IntegerField(),
            ))
        ) 
Example #23
Source File: sites.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_site_for_hostname(hostname, port):
    """Return the wagtailcore.Site object for the given hostname and port."""
    Site = apps.get_model('wagtailcore.Site')

    sites = list(Site.objects.annotate(match=Case(
        # annotate the results by best choice descending

        # put exact hostname+port match first
        When(hostname=hostname, port=port, then=MATCH_HOSTNAME_PORT),

        # then put hostname+default (better than just hostname or just default)
        When(hostname=hostname, is_default_site=True, then=MATCH_HOSTNAME_DEFAULT),

        # then match default with different hostname. there is only ever
        # one default, so order it above (possibly multiple) hostname
        # matches so we can use sites[0] below to access it
        When(is_default_site=True, then=MATCH_DEFAULT),

        # because of the filter below, if it's not default then its a hostname match
        default=MATCH_HOSTNAME,

        output_field=IntegerField(),
    )).filter(Q(hostname=hostname) | Q(is_default_site=True)).order_by(
        'match'
    ).select_related(
        'root_page'
    ))

    if sites:
        # if theres a unique match or hostname (with port or default) match
        if len(sites) == 1 or sites[0].match in (MATCH_HOSTNAME_PORT, MATCH_HOSTNAME_DEFAULT):
            return sites[0]

        # if there is a default match with a different hostname, see if
        # there are many hostname matches. if only 1 then use that instead
        # otherwise we use the default
        if sites[0].match == MATCH_DEFAULT:
            return sites[len(sites) == 2]

    raise Site.DoesNotExist() 
Example #24
Source File: filters.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def filter_queryset(self, request, queryset, view):
        """
        This performs field level filtering on the result set
        Eg: ?title=James Joyce
        """
        fields = set(view.get_available_fields(queryset.model, db_fields_only=True))

        for field_name, value in request.GET.items():
            if field_name in fields:
                try:
                    field = queryset.model._meta.get_field(field_name)
                except LookupError:
                    field = None

                # Convert value into python
                try:
                    if isinstance(field, (models.BooleanField, models.NullBooleanField)):
                        value = parse_boolean(value)
                    elif isinstance(field, (models.IntegerField, models.AutoField)):
                        value = int(value)
                except ValueError as e:
                    raise BadRequestError("field filter error. '%s' is not a valid value for %s (%s)" % (
                        value,
                        field_name,
                        str(e)
                    ))

                if isinstance(field, TaggableManager):
                    for tag in value.split(','):
                        queryset = queryset.filter(**{field_name + '__name': tag})

                    # Stick a message on the queryset to indicate that tag filtering has been performed
                    # This will let the do_search method know that it must raise an error as searching
                    # and tag filtering at the same time is not supported
                    queryset._filtered_by_tag = True
                else:
                    queryset = queryset.filter(**{field_name: value})

        return queryset 
Example #25
Source File: transforms.py    From django-tree with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def output_field(self):
        return IntegerField() 
Example #26
Source File: regexps_and_text_based_ml_field_detection.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_external_field_values(cls, field) -> List[dict]:
        return list(ExternalFieldValue.objects
                    .filter(field_id=field.pk)
                    .annotate(text_unit__textunittext__text=F('text_unit_text'))
                    .values('text_unit__textunittext__text', 'value', 'extraction_hint')
                    .annotate(created_by=Value(1, output_field=IntegerField()))[:settings.ML_TRAIN_DATA_SET_GROUP_LEN]) 
Example #27
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_false_annotations_queryset(self):
        """
        Get FieldAnnotationFalseMatch queryset
        """
        false_ann_qs = self.get_initial_queryset(FieldAnnotationFalseMatch)

        # TODO: move common annotations into get_initial_queryset()
        # WARN: fields order makes sense here for list view
        false_ann_qs = false_ann_qs.values(*self.common_fields).annotate(
            status_id=Value(FieldAnnotationStatus.rejected_status_pk(), output_field=IntegerField()),
            modified_by_id=Value(None, output_field=CharField()),
            modified_date=Value(None, output_field=DateField()),

            document_id=Cast('document_id', output_field=CharField()),
            project_id=F('document__project_id'),
            project_name=F('document__project__name'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=F('field__title'),
            status_name=Value('Rejected', output_field=CharField()),
            assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
                               When(assignee__first_name__isnull=False,
                                    assignee__last_name__isnull=False,
                                    then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
                               default=F('assignee__username'),
                               output_field=CharField()
                               )
        )
        return false_ann_qs 
Example #28
Source File: filters.py    From django_OA with 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 #29
Source File: test_bulk.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_localized_bulk_insert():
        """Tests whether bulk inserts work properly when using a
        :see:LocalizedUniqueSlugField in the model."""

        model = get_fake_model(
            {
                "name": LocalizedField(),
                "slug": LocalizedUniqueSlugField(
                    populate_from="name", include_time=True
                ),
                "score": models.IntegerField(),
            }
        )

        to_create = [
            model(
                name={"en": "english name 1", "ro": "romanian name 1"}, score=1
            ),
            model(
                name={"en": "english name 2", "ro": "romanian name 2"}, score=2
            ),
            model(
                name={"en": "english name 3", "ro": "romanian name 3"}, score=3
            ),
        ]

        model.objects.bulk_create(to_create)
        assert model.objects.all().count() == 3

        for obj in to_create:
            obj_db = model.objects.filter(
                name__en=obj.name.en, name__ro=obj.name.ro, score=obj.score
            ).first()

            assert obj_db
            assert len(obj_db.slug.en) >= len(obj_db.name.en)
            assert len(obj_db.slug.ro) >= len(obj_db.name.ro) 
Example #30
Source File: filters.py    From myblog with GNU Affero 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))