我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用django.db.models.get_models()。
def check_boolean_field_default_value(): """ Checks if there are any BooleanFields without a default value, & warns the user that the default has changed from False to Null. """ fields = [] for cls in models.get_models(): opts = cls._meta for f in opts.local_fields: if isinstance(f, models.BooleanField) and not f.has_default(): fields.append( '%s.%s: "%s"' % (opts.app_label, opts.object_name, f.name) ) if fields: fieldnames = ", ".join(fields) message = [ "You have not set a default value for one or more BooleanFields:", "%s." % fieldnames, "In Django 1.6 the default value of BooleanField was changed from", "False to Null when Field.default isn't defined. See", "https://docs.djangoproject.com/en/1.6/ref/models/fields/#booleanfield" "for more information." ] return ' '.join(message)
def _build_kml_sources(self, sources): """ Goes through the given sources and returns a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources. If no sources are provided, then all models. """ kml_sources = [] if sources is None: sources = models.get_models() for source in sources: if isinstance(source, models.base.ModelBase): for field in source._meta.fields: if isinstance(field, GeometryField): kml_sources.append((source._meta.app_label, source._meta.model_name, field.name)) elif isinstance(source, (list, tuple)): if len(source) != 3: raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).') kml_sources.append(source) else: raise TypeError('KML Sources must be a model or a 3-tuple.') return kml_sources
def handle(self, *args, **options): models = apps.get_models() script = "" for model in models: updates = get_updates_for_model(model) if updates: script += updates return script
def forwards(self, orm): "Create custom model permissions." create_permissions(models.get_app('api'), models.get_models(), 2 if settings.DEBUG else 0)
def get_model_class(table_name): """Returns a Model class based on a database table name""" classmap = dict((m._meta.db_table, m) for m in models.get_models()) if table_name in classmap: return classmap[table_name]
def handle_app(self, app, **options): connection = connections[options.get('database')] return '\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True)))
def emit_post_syncdb(verbosity, interactive, database): # Emit the post sync signal. This allows individual applications to # respond as if the database had been sync'd from scratch. all_models = [] for app in models.get_apps(): all_models.extend([ m for m in models.get_models(app, include_auto_created=True) if router.allow_syncdb(database, m) ]) emit_post_sync_signal(set(all_models), verbosity, interactive, database)
def sql_custom(app, style, connection): "Returns a list of the custom table modifying SQL statements for the given app." output = [] app_models = get_models(app) for model in app_models: output.extend(custom_sql_for_model(model, style, connection)) return output
def sql_destroy_indexes(app, style, connection): "Returns a list of the DROP INDEX SQL statements for all models in the given app." output = [] for model in models.get_models(app, include_auto_created=True): output.extend(connection.creation.sql_destroy_indexes_for_model(model, style)) return output
def model_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) m_list = [m._meta for m in models.get_models()] return render_to_response('admin_doc/model_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'models': m_list }, context_instance=RequestContext(request))
def update_permissions_after_migration(app, **kwargs): """ Update app permission just after every migration. """ create_permissions( get_app(app), get_models(), 2 if settings.DEBUG else 0)
def reset_sequences(connection, cursor, models=None): models = models or get_models(include_auto_created=True) for sql in connection.ops.sequence_reset_sql(no_style(), models): cursor.execute(sql)
def sql_create(app, style, connection): "Returns a list of the CREATE TABLE SQL statements for the given app." if connection.settings_dict['ENGINE'] == 'django.db.backends.dummy': # This must be the "dummy" database backend, which means the user # hasn't set ENGINE for the database. raise CommandError("Django doesn't know which syntax to use for your SQL statements,\n" + "because you haven't properly specified the ENGINE setting for the database.\n" + "see: https://docs.djangoproject.com/en/dev/ref/settings/#databases") # Get installed models, so we generate REFERENCES right. # We trim models from the current app so that the sqlreset command does not # generate invalid SQL (leaving models out of known_models is harmless, so # we can be conservative). app_models = models.get_models(app, include_auto_created=True) final_output = [] tables = connection.introspection.table_names() known_models = set([model for model in connection.introspection.installed_models(tables) if model not in app_models]) pending_references = {} for model in app_models: output, references = connection.creation.sql_create_model(model, style, known_models) final_output.extend(output) for refto, refs in references.items(): pending_references.setdefault(refto, []).extend(refs) if refto in known_models: final_output.extend(connection.creation.sql_for_pending_references(refto, style, pending_references)) final_output.extend(connection.creation.sql_for_pending_references(model, style, pending_references)) # Keep track of the fact that we've created the table for this model. known_models.add(model) # Handle references to tables that are from other apps # but don't exist physically. not_installed_models = set(pending_references.keys()) if not_installed_models: alter_sql = [] for model in not_installed_models: alter_sql.extend(['-- ' + sql for sql in connection.creation.sql_for_pending_references(model, style, pending_references)]) if alter_sql: final_output.append('-- The following references should be added but depend on non-existent tables:') final_output.extend(alter_sql) return final_output
def sql_delete(app, style, connection): "Returns a list of the DROP TABLE SQL statements for the given app." # This should work even if a connection isn't available try: cursor = connection.cursor() except: cursor = None # Figure out which tables already exist if cursor: table_names = connection.introspection.table_names(cursor) else: table_names = [] output = [] # Output DROP TABLE statements for standard application tables. to_delete = set() references_to_delete = {} app_models = models.get_models(app, include_auto_created=True) for model in app_models: if cursor and connection.introspection.table_name_converter(model._meta.db_table) in table_names: # The table exists, so it needs to be dropped opts = model._meta for f in opts.local_fields: if f.rel and f.rel.to not in to_delete: references_to_delete.setdefault(f.rel.to, []).append((model, f)) to_delete.add(model) for model in app_models: if connection.introspection.table_name_converter(model._meta.db_table) in table_names: output.extend(connection.creation.sql_destroy_model(model, references_to_delete, style)) # Close database connection explicitly, in case this output is being piped # directly into a database client, to avoid locking issues. if cursor: cursor.close() connection.close() return output[::-1] # Reverse it, to deal with table dependencies.
def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs): try: get_model('auth', 'Permission') except UnavailableApp: return if not router.allow_syncdb(db, auth_app.Permission): return from django.contrib.contenttypes.models import ContentType app_models = get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_models: # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(db).get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(auth_app.Permission.objects.using(db).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ auth_app.Permission(codename=codename, name=name, content_type=ctype) for ctype, (codename, name) in searched_perms if (ctype.pk, codename) not in all_perms ] auth_app.Permission.objects.using(db).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def handle(self, *app_labels, **options): # Activate project's default language translation.activate(settings.LANGUAGE_CODE) comment = options["comment"] batch_size = options["batch_size"] verbosity = int(options.get("verbosity", 1)) app_list = SortedDict() # if no apps given, use all installed. if len(app_labels) == 0: for app in models.get_apps (): if not app in app_list: app_list[app] = [] for model_class in models.get_models(app): if not model_class in app_list[app]: app_list[app].append(model_class) else: for label in app_labels: try: app_label, model_label = label.split(".") try: app = models.get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) model_class = models.get_model(app_label, model_label) if model_class is None: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) if app in app_list: if app_list[app] and model_class not in app_list[app]: app_list[app].append(model_class) else: app_list[app] = [model_class] except ValueError: # This is just an app - no model qualifier. app_label = label try: app = models.get_app(app_label) if not app in app_list: app_list[app] = [] for model_class in models.get_models(app): if not model_class in app_list[app]: app_list[app].append(model_class) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) # Create revisions. for app, model_classes in app_list.items(): for model_class in model_classes: self.create_initial_revisions(app, model_class, comment, batch_size, verbosity) # Go back to default language translation.deactivate()