我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.AutoField()。
def sequence_list(self): "Returns a list of information about all DB sequences for all models in all apps." from django.apps import apps from django.db import models, router sequence_list = [] for app_config in apps.get_app_configs(): for model in router.get_migratable_models(app_config, self.connection.alias): if not model._meta.managed: continue if model._meta.swapped: continue for f in model._meta.local_fields: if isinstance(f, models.AutoField): sequence_list.append({'table': model._meta.db_table, 'column': f.column}) break # Only one AutoField is allowed per model, so don't bother continuing. for f in model._meta.local_many_to_many: # If this is an m2m using an intermediate table, # we don't need to reset the sequence. if f.rel.through is None: sequence_list.append({'table': f.m2m_db_table(), 'column': None}) return sequence_list
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 backwards(self, orm): # Rename field 'file._file' db.rename_column('filer_file', 'file', '_file') # Deleting field 'File.is_public' db.delete_column('filer_file', 'is_public') # no need to do this. south just *thinks* something has changed, because it did not know anything about through in earlier versions # Adding M2M table for field files on 'clipboard' # db.create_table('filer_clipboard_files', ( # ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), # ('clipboard', models.ForeignKey(orm['filer.clipboard'], null=False)), # ('file', models.ForeignKey(orm['filer.file'], null=False)) # )) # db.create_unique('filer_clipboard_files', ['clipboard_id', 'file_id'])
def sequence_reset_sql(self, style, model_list): from django.db import models output = [] query = self._sequence_reset_sql for model in model_list: for f in model._meta.local_fields: if isinstance(f, models.AutoField): table_name = self.quote_name(model._meta.db_table) sequence_name = self._get_sequence_name(model._meta.db_table) column_name = self.quote_name(f.column) output.append(query % {'sequence': sequence_name, 'table': table_name, 'column': column_name}) # Only one AutoField is allowed per model, so don't # continue to loop break for f in model._meta.many_to_many: if not f.remote_field.through: table_name = self.quote_name(f.m2m_db_table()) sequence_name = self._get_sequence_name(f.m2m_db_table()) column_name = self.quote_name('id') output.append(query % {'sequence': sequence_name, 'table': table_name, 'column': column_name}) return output
def sequence_list(self): "Returns a list of information about all DB sequences for all models in all apps." from django.apps import apps from django.db import models, router sequence_list = [] for app_config in apps.get_app_configs(): for model in router.get_migratable_models(app_config, self.connection.alias): if not model._meta.managed: continue if model._meta.swapped: continue for f in model._meta.local_fields: if isinstance(f, models.AutoField): sequence_list.append({'table': model._meta.db_table, 'column': f.column}) break # Only one AutoField is allowed per model, so don't bother continuing. for f in model._meta.local_many_to_many: # If this is an m2m using an intermediate table, # we don't need to reset the sequence. if f.remote_field.through is None: sequence_list.append({'table': f.m2m_db_table(), 'column': None}) return sequence_list
def change_models(self, queryset, cleaned_data): n = queryset.count() data = {} fields = self.opts.fields + self.opts.many_to_many for f in fields: if not f.editable or isinstance(f, models.AutoField) \ or not f.name in cleaned_data: continue data[f] = cleaned_data[f.name] if n: for obj in queryset: for f, v in data.items(): f.save_form_data(obj, v) obj.save() self.message_user(_("Successfully change %(count)d %(items)s.") % { "count": n, "items": model_ngettext(self.opts, n) }, 'success')
def construct_instance(form, instance, fields=None, exclude=None): """ Constructs and returns a model instance from the bound ``form``'s ``cleaned_data``, but does not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_data file_field_list = [] for f in opts.fields: if not f.editable or isinstance(f, models.AutoField) \ or f.name not in cleaned_data: continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue # Leave defaults for fields that aren't in POST data, except for # checkbox inputs because they don't appear in POST data if not checked. if (f.has_default() and form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))): continue # Defer saving file-type fields until after the other fields, so a # callable upload_to can use the values from other fields. if isinstance(f, models.FileField): file_field_list.append(f) else: f.save_form_data(instance, cleaned_data[f.name]) for f in file_field_list: f.save_form_data(instance, cleaned_data[f.name]) return instance # ModelForms #################################################################
def sequence_reset_sql(self, style, model_list): from django.db import models output = [] query = self._sequence_reset_sql for model in model_list: for f in model._meta.local_fields: if isinstance(f, models.AutoField): table_name = self.quote_name(model._meta.db_table) sequence_name = self._get_sequence_name(model._meta.db_table) column_name = self.quote_name(f.column) output.append(query % {'sequence': sequence_name, 'table': table_name, 'column': column_name}) # Only one AutoField is allowed per model, so don't # continue to loop break for f in model._meta.many_to_many: if not f.rel.through: table_name = self.quote_name(f.m2m_db_table()) sequence_name = self._get_sequence_name(f.m2m_db_table()) column_name = self.quote_name('id') output.append(query % {'sequence': sequence_name, 'table': table_name, 'column': column_name}) return output
def forwards(self, orm): # Adding model 'Project' db.create_table('api_project', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), ('organization', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_organization', to=orm['auth.User'])), ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_creator', to=orm['auth.User'])), ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), )) db.send_create_signal('api', ['Project']) # Adding unique constraint on 'Project', fields ['name', 'organization'] db.create_unique('api_project', ['name', 'organization_id']) # Adding M2M table for field projects on 'Team' db.create_table('api_team_projects', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('team', models.ForeignKey(orm['api.team'], null=False)), ('project', models.ForeignKey(orm['api.project'], null=False)) )) db.create_unique('api_team_projects', ['team_id', 'project_id'])
def change_models(self, queryset, cleaned_data): n = queryset.count() data = {} for f in self.opts.fields: if not f.editable or isinstance(f, models.AutoField) \ or not f.name in cleaned_data: continue data[f] = cleaned_data[f.name] if n: for obj in queryset: for f, v in data.items(): f.save_form_data(obj, v) obj.save() self.message_user(_("Successfully change %(count)d %(items)s.") % { "count": n, "items": model_ngettext(self.opts, n) }, 'success')
def forwards(self, orm): # Adding model 'Project' db.create_table(u'projects_project', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('team', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['teams.Team'], null=True, blank=True)), ('added_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='added_projects', to=orm['accounts.Account'])), ('name', self.gf('django.db.models.fields.CharField')(max_length=32)), ('description', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal(u'projects', ['Project']) # Adding M2M table for field members on 'Project' m2m_table_name = db.shorten_name(u'projects_project_members') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('project', models.ForeignKey(orm[u'projects.project'], null=False)), ('account', models.ForeignKey(orm[u'accounts.account'], null=False)) )) db.create_unique(m2m_table_name, ['project_id', 'account_id'])
def forwards(self, orm): # Adding field 'Account.is_superuser' db.add_column(u'accounts_account', 'is_superuser', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) # Adding M2M table for field groups on 'Account' m2m_table_name = db.shorten_name(u'accounts_account_groups') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('account', models.ForeignKey(orm[u'accounts.account'], null=False)), ('group', models.ForeignKey(orm[u'auth.group'], null=False)) )) db.create_unique(m2m_table_name, ['account_id', 'group_id']) # Adding M2M table for field user_permissions on 'Account' m2m_table_name = db.shorten_name(u'accounts_account_user_permissions') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('account', models.ForeignKey(orm[u'accounts.account'], null=False)), ('permission', models.ForeignKey(orm[u'auth.permission'], null=False)) )) db.create_unique(m2m_table_name, ['account_id', 'permission_id'])
def change_models(self, queryset, cleaned_data): n = queryset.count() data = {} for f in self.opts.fields: if not f.editable or isinstance(f, models.AutoField) \ or not f.name in cleaned_data: continue data[f] = cleaned_data[f.name] if n: for obj in queryset: for f, v in list(data.items()): f.save_form_data(obj, v) obj.save() self.message_user(_("Successfully change %(count)d %(items)s.") % { "count": n, "items": model_ngettext(self.opts, n) }, 'success')
def test_migrations_apply_to_templates(self): template = SchemaTemplate.objects.create(name='a') 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) template.activate() self.assertFalse('tests_pony' in get_table_list()) with connection.schema_editor() as editor: operation.database_forwards('tests', editor, project_state, new_state) template.activate() self.assertTrue('tests_pony' in get_table_list()) with connection.schema_editor() as editor: operation.database_backwards('tests', editor, new_state, project_state) template.activate() self.assertFalse('tests_pony' in get_table_list())
def change_models(self, queryset, cleaned_data): n = queryset.count() data = {} for f in self.opts.fields: if not f.editable or isinstance(f, models.AutoField) \ or not f.name in cleaned_data: continue value = cleaned_data[f.name] if value: data[f] = value if n: for obj in queryset: for f, v in data.items(): f.save_form_data(obj, v) obj.save() self.message_user(_("Successfully change %(count)d %(items)s.") % { "count": n, "items": model_ngettext(self.opts, n) }, 'success')
def backwards(self, orm): # Adding model 'View' db.create_table('sentry_view', ( ('path', self.gf('django.db.models.fields.CharField')(max_length=100, unique=True)), ('verbose_name', self.gf('django.db.models.fields.CharField')(max_length=200, null=True)), ('id', self.gf('sentry.db.models.fields.bounded.BoundedBigAutoField')(primary_key=True)), ('verbose_name_plural', self.gf('django.db.models.fields.CharField')(max_length=200, null=True)), )) db.send_create_signal('sentry', ['View']) # Adding M2M table for field views on 'Group' db.create_table('sentry_groupedmessage_views', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('group', self.gf('sentry.db.models.fields.FlexibleForeignKey')(orm['sentry.group'], null=False)), ('view', self.gf('sentry.db.models.fields.FlexibleForeignKey')(orm['sentry.view'], null=False)) )) db.create_unique('sentry_groupedmessage_views', ['group_id', 'view_id'])
def forwards(self, orm): # Adding model 'Tag' db.create_table('maasserver_tag', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('created', self.gf('django.db.models.fields.DateTimeField')()), ('updated', self.gf('django.db.models.fields.DateTimeField')()), ('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=256)), ('definition', self.gf('django.db.models.fields.TextField')()), ('comment', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal('maasserver', ['Tag']) # Adding M2M table for field tags on 'Node' db.create_table('maasserver_node_tags', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('node', models.ForeignKey(orm['maasserver.node'], null=False)), ('tag', models.ForeignKey(orm['maasserver.tag'], null=False)) )) db.create_unique('maasserver_node_tags', ['node_id', 'tag_id'])
def forwards(self, orm): # Adding field 'StaticIPAddress.subnet' db.add_column('maasserver_staticipaddress', 'subnet', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['maasserver.Subnet'], null=True, blank=True), keep_default=False) # Changing field 'StaticIPAddress.ip' db.alter_column('maasserver_staticipaddress', 'ip', self.gf('maasserver.fields.MAASIPAddressField')(max_length=39, unique=True, null=True)) # Adding M2M table for field ip_addresses on 'Interface' db.create_table('maasserver_interface_ip_addresses', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('interface', models.ForeignKey(orm['maasserver.interface'], null=False)), ('staticipaddress', models.ForeignKey(orm['maasserver.staticipaddress'], null=False)) )) db.create_unique('maasserver_interface_ip_addresses', ['interface_id', 'staticipaddress_id'])
def forwards(self, orm): # Adding model 'ActionStatus' db.create_table(u'Crm_actionstatus', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=200)), ('ordering', self.gf('django.db.models.fields.IntegerField')(default=10)), )) db.send_create_signal(u'Crm', ['ActionStatus']) # Adding field 'Action.status' db.add_column(u'Crm_action', 'status', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['Crm.ActionStatus'], null=True, blank=True), keep_default=False) # Adding M2M table for field allowed_status on 'ActionType' m2m_table_name = db.shorten_name(u'Crm_actiontype_allowed_status') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('actiontype', models.ForeignKey(orm[u'Crm.actiontype'], null=False)), ('actionstatus', models.ForeignKey(orm[u'Crm.actionstatus'], null=False)) )) db.create_unique(m2m_table_name, ['actiontype_id', 'actionstatus_id'])
def forwards(self, orm): # Adding M2M table for field contacts on 'Action' m2m_table_name = db.shorten_name(u'Crm_action_contacts') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('action', models.ForeignKey(orm[u'Crm.action'], null=False)), ('contact', models.ForeignKey(orm[u'Crm.contact'], null=False)) )) db.create_unique(m2m_table_name, ['action_id', 'contact_id']) # Adding M2M table for field entities on 'Action' m2m_table_name = db.shorten_name(u'Crm_action_entities') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('action', models.ForeignKey(orm[u'Crm.action'], null=False)), ('entity', models.ForeignKey(orm[u'Crm.entity'], null=False)) )) db.create_unique(m2m_table_name, ['action_id', 'entity_id'])
def forwards(self, orm): # Removing M2M table for field to on 'Emailing' db.delete_table('Emailing_emailing_to') # Adding M2M table for field send_to on 'Emailing' db.create_table('Emailing_emailing_send_to', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('emailing', models.ForeignKey(orm['Emailing.emailing'], null=False)), ('contact', models.ForeignKey(orm['Crm.contact'], null=False)) )) db.create_unique('Emailing_emailing_send_to', ['emailing_id', 'contact_id']) # Adding M2M table for field sent_to on 'Emailing' db.create_table('Emailing_emailing_sent_to', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('emailing', models.ForeignKey(orm['Emailing.emailing'], null=False)), ('contact', models.ForeignKey(orm['Crm.contact'], null=False)) )) db.create_unique('Emailing_emailing_sent_to', ['emailing_id', 'contact_id'])
def forwards(self, orm): # Adding model 'CategoryPermission' db.create_table('Profile_categorypermission', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('category', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['coop_cms.ArticleCategory'], unique=True)), )) db.send_create_signal('Profile', ['CategoryPermission']) # Adding M2M table for field can_view_groups on 'CategoryPermission' db.create_table('Profile_categorypermission_can_view_groups', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('categorypermission', models.ForeignKey(orm['Profile.categorypermission'], null=False)), ('group', models.ForeignKey(orm['Crm.group'], null=False)) )) db.create_unique('Profile_categorypermission_can_view_groups', ['categorypermission_id', 'group_id']) # Adding M2M table for field can_edit_groups on 'CategoryPermission' db.create_table('Profile_categorypermission_can_edit_groups', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('categorypermission', models.ForeignKey(orm['Profile.categorypermission'], null=False)), ('group', models.ForeignKey(orm['Crm.group'], null=False)) )) db.create_unique('Profile_categorypermission_can_edit_groups', ['categorypermission_id', 'group_id'])