我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.IntegerField()。
def getRegistrationTypesAveragesByYear(): srs = EventRegistration.objects.all() eligible_years = [x['event__year'] for x in srs.values('event__year').annotate(Count('event__year'))] eligible_years.sort() year_averages = [] for year in eligible_years: this_year_results = srs.filter(event__year=year).annotate( student=Case(When(registration__student=True,then=100),default=0,output_field=IntegerField()), door=Case(When(registration__payAtDoor=False,then=100),default=0,output_field=IntegerField()), droppedIn=Case(When(dropIn=True,then=100),default=0,output_field=IntegerField()), cancellation=Case(When(cancelled=True,then=100),default=0,output_field=IntegerField()), ).aggregate(Student=Avg('student'),Door=Avg('door'),DropIn=Avg('droppedIn'),Cancelled=Avg('cancellation'),year=Min('event__year')) year_averages.append(this_year_results) return year_averages
def set_up_test_model(self): operations = [ migrations.CreateModel( "Pony", [ ('pony_id', models.AutoField(primary_key=True)), ('pink', models.IntegerField(default=3)), ('weight', models.FloatField()) ], ), migrations.CreateModel( 'Rider', [ ('rider_id', models.AutoField(primary_key=True)), ('pony', models.ForeignKey('Pony', on_delete=models.CASCADE)) ], ), ] return self.apply_operations('tests', ProjectState(), operations)
def test_demo_schemata_get_migrated(self): user = User.objects.create_user(**CREDENTIALS) schema = DemoSchema.objects.create(user=user, from_template=self.template) operation = migrations.CreateModel("Pony", [ ('pony_id', models.AutoField(primary_key=True)), ('pink', models.IntegerField(default=1)), ]) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards('tests', new_state) schema.activate() self.assertFalse('tests_pony' in get_table_list()) with connection.schema_editor() as editor: operation.database_forwards('tests', editor, project_state, new_state) schema.activate() self.assertTrue('tests_pony' in get_table_list()) with connection.schema_editor() as editor: operation.database_backwards('tests', editor, new_state, project_state) schema.activate() self.assertFalse('tests_pony' in get_table_list())
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 smart_text(value)
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)
def set_end_dates(self): """ Set the end_date for each Membership based on the start_date of each successor. """ for member in Membership.objects.all(): # Each member's end year should be the start year of their successor. # Successor is the member in the same post with the earliest # start year greater than the incumbent's start year if member.start_date == '': start_year = 0 else: start_year = int(member.start_date) successor_q = Membership.objects.exclude( start_date='', ).annotate( start_year=Cast('start_date', IntegerField()), ).filter( start_year__gt=start_year, post=member.post, ).order_by('start_year') if successor_q.exists(): member.end_date = int(successor_q[0].start_date) member.save()
def get_user_languages(self, language_preferences): """ Get the best matching Languages for a list of preferences, in order from best to worst. All languages will appear in the queryset. """ # Scores: Matched languages will get a score depending upon their # preference - better languages will get a higher score, down to 0 for # the 'worst' preferenced language. The default language will get a # score or -1 unless it matched as a preference, and all other # languages will get a score of -2 # `When` clauses for all the preferred languages clauses = [ When(code__iexact=language, then=Value(i)) for i, language in enumerate(reversed(language_preferences))] # The default language gets a score of -1 clauses.append(When(is_default=True, then=Value(-1))) return self.annotate( score=Case( *clauses, default=Value(-2), # Everything else gets -2 output_field=models.IntegerField(null=True)) ).order_by('-score', 'order')
def serve(self, request): language_preferences = get_request_language_preference(request) languages = Language.objects.get_user_languages(language_preferences) candidate_pages = TranslatedPage.objects\ .live().specific()\ .child_of(self)\ .filter(language__in=languages)\ .annotate(language_score=Case( *[When(language=language, then=Value(i)) for i, language in enumerate(languages)], default=Value(None), output_field=models.IntegerField(null=True)))\ .order_by('language_score') translation = candidate_pages.first() if translation: # Redirect to the best translation return redirect(translation.url) else: # No translation was found, not even in the default language! Oh dear. raise Http404
def mantaince(self): if datetime.date.today() - self.updated_at.days > 30: self.prog_stats["no_of_users_this_month"] = 0 # class ProgStat(models.Model): # ''' # no_of_users: integer # no_of_users_this_month: integer # ''' # no_of_users = models.IntegerField(default='0') # no_of_users_this_month = models.IntegerField(default='0') # class Mentors(models.Model): # ''' # Mentor name and id # ''' # name = models.CharField(max_length=64) # mid = models.IntegerField(default='0')
def reload_reply(request): """API reload_reply""" if request.method == 'POST': id = request.POST['id'] replies = Reply.objects.filter(article_id=id).annotate( custom_order=Case( When(reply_id=0, then='id'), default='reply_id', output_field=IntegerField(), ) ).order_by('custom_order', 'id') article = get_object_or_404(Board, pk=id) return render_to_response( 'boards/show_reply.html', { 'user': request.user, 'article_user': article.user, 'replies': replies, 'count': replies.count() } ) else: return error_to_response(request)
def reload_team_reply(request): """API reload_team_reply""" if request.method == 'POST': id = request.POST['id'] replies = TeamReply.objects.filter(article_id=id).annotate( custom_order=Case( When(reply_id=0, then='id'), default='reply_id', output_field=IntegerField(), ) ).order_by('custom_order', 'id') article = get_object_or_404(Team, pk=id) return render_to_response( 'teams/show_team_reply.html', { 'user': request.user, 'article_user': article.user, 'replies': replies, 'count': replies.count() } ) else: return error_to_response(request)
def show_reply(context, id): """Show replies""" replies = Reply.objects.filter(article_id=id).annotate( custom_order=Case( When(reply_id=0, then='id'), default='reply_id', output_field=IntegerField(), ) ).order_by('custom_order', 'id') user = context['request'].user article = get_object_or_404(Board, pk=id) return { 'user': user, 'article_user': article.user, 'replies': replies, 'count': replies.count() }
def show_team_reply(context, id): """Show team replies""" replies = TeamReply.objects.filter(article_id=id).annotate( custom_order=Case( When(reply_id=0, then='id'), default='reply_id', output_field=IntegerField(), ) ).order_by('custom_order', 'id') user = context['request'].user article = get_object_or_404(Team, pk=id) return { 'user': user, 'article_user': article.user, 'replies': replies, 'count': replies.count() }
def show_comment(context, id): """Show comments""" q = Q(status='1normal') comments = Comment.objects.filter(post_id=id).filter(q).annotate( custom_order=Case( When(comment_id=0, then='id'), default='comment_id', output_field=IntegerField(), ) ).order_by('custom_order', 'id') user = context['request'].user post = get_object_or_404(Blog, pk=id) return { 'user': user, 'post_user': post.user.username, 'comments': comments, 'count': comments.count() }
def annotate_queryset(self, queryset, request): self.get_skills_and_causes(request) queryset = queryset\ .annotate(\ cause_relevance = Count( Case(When(causes__pk__in=[1,3], then=1), output_field=IntegerField()), distinct=True), skill_relevance = Count( Case(When(skills__pk__in=[1,2,4], then=1), output_field=IntegerField()), distinct=True))\ .annotate(relevance = F('cause_relevance') + F('skill_relevance')) return queryset
def popularVouchersJSON(request): startDate = getDateTimeFromGet(request,'startDate') endDate = getDateTimeFromGet(request,'endDate') timeLimit = Q(voucheruse__creationDate__isnull=False) if startDate: timeLimit = timeLimit & Q(voucheruse__creationDate__gte=startDate) if endDate: timeLimit = timeLimit & Q(voucheruse__creationDate__lte=endDate) uses = list(Voucher.objects.annotate( counter=Count(Case( When(timeLimit, then=1), output_field=IntegerField()) )).filter(counter__gt=0).values('name','counter').order_by('-counter')[:10]) return JsonResponse(uses,safe=False)
def popularDiscountsJSON(request): startDate = getDateTimeFromGet(request,'startDate') endDate = getDateTimeFromGet(request,'endDate') timeLimit = Q(registrationdiscount__registration__dateTime__isnull=False) if startDate: timeLimit = timeLimit & Q(registrationdiscount__registration__dateTime__gte=startDate) if endDate: timeLimit = timeLimit & Q(registrationdiscount__registration__dateTime__lte=endDate) uses = list(DiscountCombo.objects.annotate( counter=Count(Case( When(timeLimit, then=1), output_field=IntegerField()) )).filter(counter__gt=0).values('name','counter').order_by('-counter')[:10]) return JsonResponse(uses,safe=False)
def test_basic_model_message(self): class MockMessage(DjangoProtoRPCMessage): class Meta: model = DummyModel self.assertIsSubclass(MockMessage, messages.Message) self.assertIsInstance(MockMessage.foo, messages.StringField) self.assertIsInstance(MockMessage.whizz_id, messages.IntegerField) self.assertIsInstance(MockMessage.bar_id, messages.IntegerField) self.assertIsInstance(MockMessage.default, messages.BooleanField) self.assertTrue(MockMessage.foo.required) self.assertFalse(MockMessage.default.required) self.assertFalse(hasattr(MockMessage, 'bar')) self.assertFalse(hasattr(MockMessage, 'foobars')) self.assertFalse(hasattr(MockMessage, 'foobar_ids'))
def test_basic_model_message_with_excludes(self): class MockMessage(DjangoProtoRPCMessage): class Meta: model = DummyModel exclude = ('bar',) self.assertIsSubclass(MockMessage, messages.Message) self.assertIsInstance(MockMessage.foo, messages.StringField) self.assertIsInstance(MockMessage.whizz_id, messages.IntegerField) self.assertTrue(MockMessage.foo.required) self.assertFalse(hasattr(MockMessage, 'bar_id')) self.assertFalse(hasattr(MockMessage, 'bar')) self.assertFalse(hasattr(MockMessage, 'foobars')) self.assertFalse(hasattr(MockMessage, 'foobar_ids'))
def test_basic_model_include_related(self): class MockMessage(DjangoProtoRPCMessage): class Meta: model = DummyModel include_related_ids = True self.assertIsSubclass(MockMessage, messages.Message) self.assertIsInstance(MockMessage.foo, messages.StringField) self.assertIsInstance(MockMessage.whizz_id, messages.IntegerField) self.assertIsInstance(MockMessage.bar_id, messages.IntegerField) self.assertIsInstance(MockMessage.foobar_ids, messages.IntegerField) self.assertTrue(MockMessage.foobar_ids.repeated) self.assertTrue(MockMessage.foo.required) self.assertFalse(hasattr(MockMessage, 'bar')) self.assertFalse(hasattr(MockMessage, 'foobars'))
def relevant_reqs_count(params): """Create a subquery of the count of requirements relevant to the provided query parameters""" subquery = Requirement.objects.filter(policy=OuterRef('pk')) params = subfilter_params(params, 'requirements') subquery = RequirementFilter(params, queryset=subquery).qs subquery = filter_by_topic(params, subquery) subquery = filter_by_agency(params, subquery) subquery = filter_by_agency_group(params, subquery) subquery = filter_by_all_agency(params, subquery) subquery = subquery.filter(public=True) subquery = subquery.values('policy').\ annotate(count=Count('policy')).values('count').\ order_by() # clear default order return Subquery(subquery, output_field=IntegerField())
def test_add_unique_constraint(self): project_state = self.set_up_test_model() operation = migrations.AlterField( model_name='pony', name='pink', field=models.IntegerField(unique=True, default=3) ) new_state = project_state.clone() operation.state_forwards('tests', new_state) self.assertNoConstraint('tests_pony', ['pink'], 'unique') with connection.schema_editor() as editor: operation.database_forwards('tests', editor, project_state, new_state) self.assertConstraint('tests_pony', ['pink'], 'unique') with connection.schema_editor() as editor: operation.database_backwards('tests', editor, new_state, project_state) self.assertNoConstraint('tests_pony', ['pink'], 'unique')
def reorder(_default=AFTER, _reverse=False, **kwargs): """ Return a database expression that can be used in an order_by() so that the queryset will be sorted according to the order of values given. """ if not 0 < len(kwargs) <= 1: raise TypeError("reorder() takes one non-optional keyword argument") fieldname, new_order = kwargs.popitem() if _default is BEFORE: _default = -1 elif _default is AFTER: _default = len(new_order) whens = [When(**{fieldname: v, 'then': i}) for i, v in enumerate(new_order)] casewhen = Case(*whens, default=Value(_default), output_field=IntegerField()) if _reverse: return casewhen.desc() else: return casewhen.asc()
def order_by_amount_raised(self): return self.annotate( amount_raised=models.Sum( models.Case( models.When( project__campaign__investment__charge__paid=True, project__campaign__investment__charge__refunded=False, then=( models.F('project__campaign__investment__num_shares') * models.F('project__campaign__value_per_share') ), ), default=0, output_field=models.IntegerField() ) ) ).order_by('-amount_raised')
def test_operation_is_safe(self): assert migration_utils.operation_is_safe(operations.AddField( model_name='unsafemodel', name='safe_field', field=models.IntegerField(null=True), )) assert migration_utils.operation_is_safe(operations.AddField( model_name='unsafemodel', name='field_added', field=models.IntegerField(default=1), preserve_default=False, )) is False assert migration_utils.operation_is_safe(operations.AlterField( model_name='unsafemodel', name='field_added', field=models.PositiveIntegerField(default=10), preserve_default=False )) is False assert migration_utils.operation_is_safe(operations.RenameField( model_name='unsafemodel', old_name='field_added', new_name='field_renamed' )) is False assert migration_utils.operation_is_safe(operations.RemoveField( model_name='unsafemodel', name='field_renamed', )) is False assert migration_utils.operation_is_safe(operations.DeleteModel('unsafemodel')) is False assert migration_utils.operation_is_safe(operations.RunSQL("")) is False assert migration_utils.operation_is_safe(operations.RunPython(lambda: True)) is False
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))
def __init__(self, y, x): super(RegrCount, self).__init__(y=y, x=x, output_field=IntegerField())
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.target_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)
def test_translation_unsupported_field(self): class IntegerModel(models.Model): integer = models.IntegerField() i18n = TranslationField(fields=('integer', )) class Meta: app_label = 'django-modeltrans_tests' expected_message = 'IntegerField is not supported by django-modeltrans.' with self.assertRaisesMessage(ImproperlyConfigured, expected_message): translate_model(IntegerModel)