本文整理汇总了Python中django.db.models.IntegerField方法的典型用法代码示例。如果您正苦于以下问题:Python models.IntegerField方法的具体用法?Python models.IntegerField怎么用?Python models.IntegerField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.IntegerField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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
示例2: filter_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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')
示例3: filter_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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')
示例4: display_for_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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)
示例5: redirect_staff
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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)
示例6: get_queue_size_params
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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
示例7: get
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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
示例8: create_closure_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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
示例9: display_for_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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)
示例10: threads
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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})
示例11: display_for_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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)
示例12: display_for_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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)
示例13: test
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
def test(cls, field, request, params, model, admin_view, field_path):
return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField))
示例14: list_with_post
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
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)
示例15: default_storage_location
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import IntegerField [as 别名]
def default_storage_location(self) -> Optional["StorageLocation"]:
"""Return default storage location for this instance.
This is a storage location using connector with the lowest priority.
When multiple storage locations have same priority one of them is
returned.
Usually only StorageLocation objects with status OK are considered.
When no such objects exist one of remaining objects is returned (this
should only happen when data object is still processing). When no
StorageLocation objects exist None is returned.
When StorageLocation has ceonnector that is not defined in settings the
default priority of 100 is applied to it.
:returns: instance of StorageLocation class or None.
:rtype: Optional[StorageLocation]
"""
whens = [
models.When(
connector_name=connector_name, then=connectors[connector_name].priority,
)
for connector_name in connectors
]
q_set_all = self.storage_locations.annotate(
priority=models.Case(
*whens,
default=DEFAULT_CONNECTOR_PRIORITY,
output_field=models.IntegerField(),
)
).order_by("priority")
q_set_done = q_set_all.filter(status=StorageLocation.STATUS_DONE)
return q_set_done.first() or q_set_all.first()