def test_ticket_11936(self): # Regression for #11936 - loading.get_models should not return deferred # models by default. # Run a couple of defer queries so that app-cache must contain some # deferred classes. It might contain a lot more classes depending on # the order the tests are ran. list(Item.objects.defer("name")) list(Child.objects.defer("value")) klasses = set( map(attrgetter("__name__"), cache.get_models(cache.get_app("defer_regress")))) self.assertIn("Child", klasses) self.assertIn("Item", klasses) self.assertNotIn("Child_Deferred_value", klasses) self.assertNotIn("Item_Deferred_name", klasses) self.assertFalse( any(k._deferred for k in cache.get_models(cache.get_app("defer_regress")))) klasses_with_deferred = set( map( attrgetter("__name__"), cache.get_models(cache.get_app("defer_regress"), include_deferred=True), )) self.assertIn("Child", klasses_with_deferred) self.assertIn("Item", klasses_with_deferred) self.assertIn("Child_Deferred_value", klasses_with_deferred) self.assertIn("Item_Deferred_name", klasses_with_deferred) self.assertTrue( any(k._deferred for k in cache.get_models(cache.get_app("defer_regress"), include_deferred=True)))
def test_ticket_11936(self): # Regression for #11936 - loading.get_models should not return deferred # models by default. # Run a couple of defer queries so that app-cache must contain some # deferred classes. It might contain a lot more classes depending on # the order the tests are ran. list(Item.objects.defer("name")) list(Child.objects.defer("value")) klasses = set(map(attrgetter("__name__"), cache.get_models(cache.get_app("defer_regress")))) self.assertIn("Child", klasses) self.assertIn("Item", klasses) self.assertNotIn("Child_Deferred_value", klasses) self.assertNotIn("Item_Deferred_name", klasses) self.assertFalse(any(k._deferred for k in cache.get_models(cache.get_app("defer_regress")))) klasses_with_deferred = set( map(attrgetter("__name__"), cache.get_models(cache.get_app("defer_regress"), include_deferred=True)) ) self.assertIn("Child", klasses_with_deferred) self.assertIn("Item", klasses_with_deferred) self.assertIn("Child_Deferred_value", klasses_with_deferred) self.assertIn("Item_Deferred_name", klasses_with_deferred) self.assertTrue( any(k._deferred for k in cache.get_models(cache.get_app("defer_regress"), include_deferred=True)) ) # Regression for #16409 - make sure defer() and only() work with annotate() self.assertIsInstance(list(SimpleItem.objects.annotate(Count("feature")).defer("name")), list) self.assertIsInstance(list(SimpleItem.objects.annotate(Count("feature")).only("name")), list)
def ask_initial(self, app_label): "Should we create an initial migration for the app?" # Don't ask for django.contrib apps app = cache.get_app(app_label) if app.__name__.startswith("django.contrib"): return False # If it was specified on the command line, definitely true if app_label in self.specified_apps: return True # Now ask return self._boolean_input("Do you want to enable migrations for app '%s'? [y/N]" % app_label, False)
def flush_cache(apps, options): """ Clears the image cache """ spec_class_list = options['spec_class'] apps = [a.strip(',') for a in apps] for app_label in apps: app = cache.get_app(app_label) models = [m for m in cache.get_models(app) if issubclass(m, ImageModel)] if apps: for app_label in apps: app = cache.get_app(app_label) models = [m for m in cache.get_models(app) if issubclass(m, ImageModel)] for model in models: print 'Flushing cache for "%s.%s"' % (app_label, model.__name__) for obj in model.objects.order_by('-pk'): if spec_class_list: for spec_name in spec_class_list: try: spec = model._ik.specs[spec_name] except KeyError: print('Model %s has no spec named %s' % (model.__name__, spec_name)) continue prop = getattr(obj, spec.name(), None) if prop is not None: prop._delete() if spec.pre_cache: print('Creating %s: %d' % (spec_name,obj.id)) prop._create() else: for spec in model._ik.specs.values(): print('Flushing item %d' % obj.pk) prop = getattr(obj, spec.name(), None) if prop is not None: prop._delete() if spec.pre_cache: prop._create() else: print 'Please specify one or more app names'
def get_app(app_label, emptyOK=False): """Return the app with the given label. This returns the app from the app registry on Django >= 1.7, and from the old-style cache on Django < 1.7. The ``emptyOK`` argument is ignored for Django >= 1.7. """ if apps: return apps.get_app(app_label) else: return cache.get_app(app_label, emptyOK)
def test_dynamic_load(self): """ Makes a new model at runtime and ensures it goes into the right place. """ old_models = cache.get_models(cache.get_app("app_cache")) # Construct a new model in a new app cache body = {} new_app_cache = BaseAppCache() meta_contents = { 'app_label': "app_cache", 'app_cache': new_app_cache, } meta = type("Meta", tuple(), meta_contents) body['Meta'] = meta body['__module__'] = TotallyNormal.__module__ temp_model = type("SouthPonies", (models.Model,), body) # Make sure it appeared in the right place! self.assertEqual( old_models, cache.get_models(cache.get_app("app_cache")), ) self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model)
def flush_cache(apps, options): apps = [a.strip(',') for a in apps] if apps: for app_label in apps: app = cache.get_app(app_label) for model in [m for m in cache.get_models(app)]: print 'Flushing cache for "%s.%s"' % (app_label, model.__name__) for obj in model.objects.order_by('-pk'): for spec_file in get_spec_files(obj): spec_file.delete(save=False) if spec_file.field.pre_cache: spec_file.generate(False) else: print 'Please specify one or more app names'
def path(self): migrations_module_name = MigrationLoader.migrations_module(self.migration.app_label) app_module = cache.get_app(self.migration.app_label) # See if we can import the migrations module directly try: migrations_module = import_module(migrations_module_name) basedir = os.path.dirname(migrations_module.__file__) except ImportError: # Alright, see if it's a direct submodule of the app oneup = ".".join(migrations_module_name.split(".")[:-1]) app_oneup = ".".join(app_module.__name__.split(".")[:-1]) if oneup == app_oneup: basedir = os.path.join(os.path.dirname(app_module.__file__), migrations_module_name.split(".")[-1]) else: raise ImportError("Cannot open migrations module %s for app %s" % (migrations_module_name, self.migration.app_label)) return os.path.join(basedir, self.filename)
def get_app(app_label, emptyOK=False): """Return the app with the given label. This returns the app from the app registry on Django >= 1.7, and from the old-style cache on Django < 1.7. The ``emptyOK`` argument is ignored for Django >= 1.7. Args: app_label (str): The label for the app containing the models. emptyOK (bool, optional): Impacts the return value if the app has no models in it. Returns: module: The app module, if available. If not available, and ``emptyOK`` is set, this will return ``None``. If ``emptyOK`` is not set, it will raise :py:exc:`~django.core.exceptions.ImproperlyConfigured`. Raises: django.core.exceptions.ImproperlyConfigured: The app module was not found, and ``emptyOK`` was ``False``. """ if apps: # Django >= 1.7 try: models_module = apps.get_app_config(app_label).models_module except LookupError as e: # Convert this to an ImproperlyConfigured. raise ImproperlyConfigured(*e.args) if models_module is None: if emptyOK: raise LookupError('..') raise ImproperlyConfigured( 'App with label %s is missing a models.py module.' % app_label) return models_module else: # Django < 1.7 return cache.get_app(app_label, emptyOK)
def main(): DATE=datetime.today().date() # Datestamp e.g 2002-09-21 DOW=datetime.today().strftime("%A") # Day of the week e.g. Monday # DOM=datetime.today().day # Date of the Month e.g. 27 # M=datetime.today().strftime("%B") # Month e.g January # W=datetime.today().strftime("%W") # Week Number e.g 37 # Borramos el fichero de la/s semana/s pasada/s os.system("rm -fv %s/*.rtg2.%s.sql.gz" % (settings.MYSQL_BACKUP_DIR, DOW)) rtg_models=cache.get_models(cache.get_app('rtg')) all_models = [model._meta.db_table for model in rtg_models] all_models_text = " ".join(all_models) fichero_backup ="%s/%s.rtg2.%s.sql" % (settings.MYSQL_BACKUP_DIR, DATE, DOW) dtb = settings.DATABASES['default'] os.system("mysqldump -c --user=%s --password=%s --host=%s -f %s %s > %s" % ( dtb['USER'], dtb['PASSWORD'], dtb['HOST'], dtb['NAME'], all_models_text, fichero_backup)) os.system("gzip -f %s" % (fichero_backup,))
def ask_initial(self, app_label): "Should we create an initial migration for the app?" # If it was specified on the command line, definitely true if app_label in self.specified_apps: return True # Otherwise, we look to see if it has a migrations module # without any Python files in it, apart from __init__.py. # Apps from the new app template will have these; the python # file check will ensure we skip South ones. models_module = cache.get_app(app_label) migrations_import_path = "%s.migrations" % models_module.__package__ try: migrations_module = importlib.import_module(migrations_import_path) except ImportError: return False else: filenames = os.listdir(os.path.dirname(migrations_module.__file__)) return not any(x.endswith(".py") for x in filenames if x != "__init__.py")
def path(self): migrations_package_name = MigrationLoader.migrations_module(self.migration.app_label) # See if we can import the migrations module directly try: migrations_module = import_module(migrations_package_name) basedir = os.path.dirname(migrations_module.__file__) except ImportError: app = cache.get_app(self.migration.app_label) app_path = cache._get_app_path(app) app_package_name = cache._get_app_package(app) migrations_package_basename = migrations_package_name.split(".")[-1] # Alright, see if it's a direct submodule of the app if '%s.%s' % (app_package_name, migrations_package_basename) == migrations_package_name: basedir = os.path.join(app_path, migrations_package_basename) else: raise ImportError("Cannot open migrations module %s for app %s" % (migrations_package_name, self.migration.app_label)) return os.path.join(basedir, self.filename)
def get_app(app_label, emptyOK=False): """Return the app with the given label. This returns the app from the app registry on Django >= 1.7, and from the old-style cache on Django < 1.7. app_label (str): The label for the app containing the models. emptyOK (bool, optional): Impacts the return value if the app has no models in it. Returns: module: The app module, if available. If the app module is available, but the models module is not and ``emptyOK`` is set, this will return ``None``. Otherwise, if modules are not available, this will raise :py:exc:`~django.core.exceptions.ImproperlyConfigured`. Raises: django.core.exceptions.ImproperlyConfigured: The app module was not found, or it was found but a models module was not and ``emptyOK`` was ``False``. """ if apps: # Django >= 1.7 try: models_module = apps.get_app_config(app_label).models_module except LookupError as e: # Convert this to an ImproperlyConfigured. raise ImproperlyConfigured(*e.args) if models_module is None and not emptyOK: # This is the exact error that Django 1.6 provided. raise ImproperlyConfigured( 'App with label %s is missing a models.py module.' % app_label) return models_module else: # Django < 1.7 return cache.get_app(app_label, emptyOK)
def ask_initial(self, app_label): "Should we create an initial migration for the app?" # If it was specified on the command line, definitely true if app_label in self.specified_apps: return True # Otherwise, we look to see if it has a migrations module # without any Python files in it, apart from __init__.py. # Apps from the new app template will have these; the python # file check will ensure we skip South ones. models_module = cache.get_app(app_label) migrations_import_path = "%s.migrations" % models_module.__package__ try: migrations_module = importlib.import_module(migrations_import_path) except ImportError: return False else: filenames = os.listdir(os.path.dirname(migrations_module.__file__)) return not any( x.endswith(".py") for x in filenames if x != "__init__.py")
def flush_cache(apps, options): """ Clears the image cache """ apps = [a.strip(',') for a in apps] if apps: for app_label in apps: app = cache.get_app(app_label) models = [m for m in cache.get_models(app) if issubclass(m, ImageModel)] for model in models: print 'Flushing cache for "%s.%s"' % (app_label, model.__name__) for obj in model.objects.all(): for spec in model._ik.specs: prop = getattr(obj, spec.name(), None) if prop is not None: prop._delete() if spec.pre_cache: prop._create() else: print 'Please specify on or more app names'
def flush_cache(apps, options): """ Clears the image cache """ apps = [a.strip(',') for a in apps] if apps: for app_label in apps: app = cache.get_app(app_label) models = [ m for m in cache.get_models(app) if issubclass(m, ImageModel) ] for model in models: print 'Flushing cache for "%s.%s"' % (app_label, model.__name__) for obj in model.objects.iterator(): for spec in model._ik.specs: prop = getattr(obj, spec.name(), None) if prop is not None: prop._delete() if spec.pre_cache: prop._create() else: print 'Please specify on or more app names'
def flush_cache(apps, options): """ Clears the image cache """ apps = [a.strip(',') for a in apps] if apps: print 'Flushing cache for %s...' % ', '.join(apps) else: print 'Flushing caches...' for app_label in apps: app = cache.get_app(app_label) models = [ m for m in cache.get_models(app) if issubclass(m, ImageModel) ] for model in models: for obj in model.objects.all(): for spec in model._ik.specs: prop = getattr(obj, spec.name(), None) if prop is not None: prop._delete() if spec.pre_cache: prop._create()
def build_suite(self, test_labels, extra_tests=None, **kwargs): """ Rewrite of the original build_suite method of the DjangoTestSuiteRunner to skip tests from the Django own test cases as they restricted to the Django ORM settings that we do not need to be set at all. """ suite = unittest.TestSuite() if test_labels: for label in test_labels: if '.' in label: suite.addTest(build_test(label)) else: app = cache.get_app(label) suite.addTest(build_suite(app)) else: for app in self.get_apps(): suite.addTest(build_suite(app)) if extra_tests: for test in extra_tests: suite.addTest(test) return reorder_suite(suite, (SimpleTestCase,))
def _get_models(apps): models = [] for app_label in apps or []: app = cache.get_app(app_label) models += [m for m in cache.get_models(app)] return models
def test_basic(self): # Deferred fields should really be deferred and not accidentally use # the field's default value just because they aren't passed to __init__ Item.objects.create(name="first", value=42) obj = Item.objects.only("name", "other_value").get(name="first") # Accessing "name" doesn't trigger a new database query. Accessing # "value" or "text" should. with self.assertNumQueries(0): self.assertEqual(obj.name, "first") self.assertEqual(obj.other_value, 0) with self.assertNumQueries(1): self.assertEqual(obj.value, 42) with self.assertNumQueries(1): self.assertEqual(obj.text, "xyzzy") with self.assertNumQueries(0): self.assertEqual(obj.text, "xyzzy") # Regression test for #10695. Make sure different instances don't # inadvertently share data in the deferred descriptor objects. i = Item.objects.create(name="no I'm first", value=37) items = Item.objects.only("value").order_by("-value") self.assertEqual(items[0].name, "first") self.assertEqual(items[1].name, "no I'm first") RelatedItem.objects.create(item=i) r = RelatedItem.objects.defer("item").get() self.assertEqual(r.item_id, i.id) self.assertEqual(r.item, i) # Some further checks for select_related() and inherited model # behavior (regression for #10710). c1 = Child.objects.create(name="c1", value=42) c2 = Child.objects.create(name="c2", value=37) Leaf.objects.create(name="l1", child=c1, second_child=c2) obj = Leaf.objects.only("name", "child").select_related()[0] self.assertEqual(obj.child.name, "c1") self.assertQuerysetEqual( Leaf.objects.select_related().only("child__name", "second_child__name"), [ "l1", ], attrgetter("name") ) # Models instances with deferred fields should still return the same # content types as their non-deferred versions (bug #10738). ctype = ContentType.objects.get_for_model c1 = ctype(Item.objects.all()[0]) c2 = ctype(Item.objects.defer("name")[0]) c3 = ctype(Item.objects.only("name")[0]) self.assertTrue(c1 is c2 is c3) # Regression for #10733 - only() can be used on a model with two # foreign keys. results = Leaf.objects.only("name", "child", "second_child").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") results = Leaf.objects.only("name", "child", "second_child", "child__name", "second_child__name").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") # Regression for #11936 - loading.get_models should not return deferred # models by default. klasses = sorted( cache.get_models(cache.get_app("defer_regress")), key=lambda klass: klass.__name__ ) self.assertEqual( klasses, [ Child, Feature, Item, ItemAndSimpleItem, Leaf, OneToOneItem, Proxy, RelatedItem, ResolveThis, SimpleItem, SpecialFeature, ] ) klasses = sorted( map( attrgetter("__name__"), cache.get_models( cache.get_app("defer_regress"), include_deferred=True ), ) ) # FIXME: This is dependent on the order in which tests are run -- # this test case has to be the first, otherwise a LOT more classes # appear. self.assertEqual( klasses, [ "Child", "Child_Deferred_value", "Feature", "Item", "ItemAndSimpleItem", "Item_Deferred_name", "Item_Deferred_name_other_value_text", "Item_Deferred_name_other_value_value", "Item_Deferred_other_value_text_value", "Item_Deferred_text_value", "Leaf", "Leaf_Deferred_child_id_second_child_id_value", "Leaf_Deferred_name_value", "Leaf_Deferred_second_child_id_value", "Leaf_Deferred_value", "OneToOneItem", "Proxy", "RelatedItem", "RelatedItem_Deferred_", "RelatedItem_Deferred_item_id", "ResolveThis", "SimpleItem", "SpecialFeature", ] )
def handle(self, *app_labels, **options): self.verbosity = int(options.get('verbosity')) self.interactive = options.get('interactive') # Make sure the app they asked for exists app_labels = set(app_labels) bad_app_labels = set() for app_label in app_labels: try: cache.get_app(app_label) except ImproperlyConfigured: bad_app_labels.add(app_label) if bad_app_labels: for app_label in bad_app_labels: self.stderr.write("App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label) sys.exit(2) # Load the current graph state. Takes a connection, but it's not used # (makemigrations doesn't look at the database state). loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) # Detect changes autodetector = MigrationAutodetector( loader.graph.project_state(), ProjectState.from_app_cache(cache), InteractiveMigrationQuestioner(specified_apps=app_labels), ) changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None) # No changes? Tell them. if not changes and self.verbosity >= 1: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) elif len(app_labels) > 1: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") return directory_created = {} for app_label, migrations in changes.items(): if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") for migration in migrations: # Describe the migration writer = MigrationWriter(migration) if self.verbosity >= 1: self.stdout.write(" %s:\n" % (self.style.MIGRATE_LABEL(writer.filename),)) for operation in migration.operations: self.stdout.write(" - %s\n" % operation.describe()) # Write it migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label, False): if not os.path.isdir(migrations_directory): os.mkdir(migrations_directory) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "wb") as fh: fh.write(migration_string)
def handle(self, *app_labels, **options): self.verbosity = int(options.get('verbosity')) self.interactive = options.get('interactive') self.dry_run = options.get('dry_run', False) self.merge = options.get('merge', False) # Make sure the app they asked for exists app_labels = set(app_labels) bad_app_labels = set() for app_label in app_labels: try: cache.get_app(app_label) except ImproperlyConfigured: bad_app_labels.add(app_label) if bad_app_labels: for app_label in bad_app_labels: self.stderr.write("App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label) sys.exit(2) # Load the current graph state. Takes a connection, but it's not used # (makemigrations doesn't look at the database state). loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() if conflicts and not self.merge: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError("Conflicting migrations detected (%s).\nTo fix them run 'python manage.py makemigrations --merge'" % name_str) # If they want to merge and there's nothing to merge, then politely exit if self.merge and not conflicts: self.stdout.write("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) # Detect changes autodetector = MigrationAutodetector( loader.graph.project_state(), ProjectState.from_app_cache(cache), InteractiveMigrationQuestioner(specified_apps=app_labels), ) changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None) # No changes? Tell them. if not changes and self.verbosity >= 1: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) elif len(app_labels) > 1: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") return directory_created = {} for app_label, app_migrations in changes.items(): if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") for migration in app_migrations: # Describe the migration writer = MigrationWriter(migration) if self.verbosity >= 1: self.stdout.write(" %s:\n" % (self.style.MIGRATE_LABEL(writer.filename),)) for operation in migration.operations: self.stdout.write(" - %s\n" % operation.describe()) # Write it if not self.dry_run: migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label, False): if not os.path.isdir(migrations_directory): os.mkdir(migrations_directory) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "wb") as fh: fh.write(migration_string)
def handle(self, *app_labels, **options): self.verbosity = int(options.get('verbosity')) self.interactive = options.get('interactive') # Make sure the app they asked for exists app_labels = set(app_labels) bad_app_labels = set() for app_label in app_labels: try: cache.get_app(app_label) except ImproperlyConfigured: bad_app_labels.add(app_label) if bad_app_labels: for app_label in bad_app_labels: self.stderr.write( "App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label) sys.exit(2) # Load the current graph state. Takes a connection, but it's not used # (makemigrations doesn't look at the database state). loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) # Detect changes autodetector = MigrationAutodetector( loader.graph.project_state(), ProjectState.from_app_cache(cache), InteractiveMigrationQuestioner(specified_apps=app_labels), ) changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None) # No changes? Tell them. if not changes and self.verbosity >= 1: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) elif len(app_labels) > 1: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") return directory_created = {} for app_label, migrations in changes.items(): if self.verbosity >= 1: self.stdout.write( self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") for migration in migrations: # Describe the migration writer = MigrationWriter(migration) if self.verbosity >= 1: self.stdout.write( " %s:\n" % (self.style.MIGRATE_LABEL(writer.filename), )) for operation in migration.operations: self.stdout.write(" - %s\n" % operation.describe()) # Write it migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label, False): if not os.path.isdir(migrations_directory): os.mkdir(migrations_directory) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "wb") as fh: fh.write(migration_string)
def test_basic(self): # Deferred fields should really be deferred and not accidentally use # the field's default value just because they aren't passed to __init__ Item.objects.create(name="first", value=42) obj = Item.objects.only("name", "other_value").get(name="first") # Accessing "name" doesn't trigger a new database query. Accessing # "value" or "text" should. def test(): self.assertEqual(obj.name, "first") self.assertEqual(obj.other_value, 0) self.assertNumQueries(0, test) def test(): self.assertEqual(obj.value, 42) self.assertNumQueries(1, test) def test(): self.assertEqual(obj.text, "xyzzy") self.assertNumQueries(1, test) def test(): self.assertEqual(obj.text, "xyzzy") self.assertNumQueries(0, test) # Regression test for #10695. Make sure different instances don't # inadvertently share data in the deferred descriptor objects. i = Item.objects.create(name="no I'm first", value=37) items = Item.objects.only("value").order_by("-value") self.assertEqual(items[0].name, "first") self.assertEqual(items[1].name, "no I'm first") RelatedItem.objects.create(item=i) r = RelatedItem.objects.defer("item").get() self.assertEqual(r.item_id, i.id) self.assertEqual(r.item, i) # Some further checks for select_related() and inherited model # behaviour (regression for #10710). c1 = Child.objects.create(name="c1", value=42) c2 = Child.objects.create(name="c2", value=37) Leaf.objects.create(name="l1", child=c1, second_child=c2) obj = Leaf.objects.only("name", "child").select_related()[0] self.assertEqual(obj.child.name, "c1") self.assertQuerysetEqual( Leaf.objects.select_related().only("child__name", "second_child__name"), ["l1"], attrgetter("name") ) # Models instances with deferred fields should still return the same # content types as their non-deferred versions (bug #10738). ctype = ContentType.objects.get_for_model c1 = ctype(Item.objects.all()[0]) c2 = ctype(Item.objects.defer("name")[0]) c3 = ctype(Item.objects.only("name")[0]) self.assertTrue(c1 is c2 is c3) # Regression for #10733 - only() can be used on a model with two # foreign keys. results = Leaf.objects.only("name", "child", "second_child").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") results = Leaf.objects.only( "name", "child", "second_child", "child__name", "second_child__name" ).select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") # Test for #12163 - Pickling error saving session with unsaved model # instances. SESSION_KEY = "2b1189a188b44ad18c35e1baac6ceead" item = Item() item._deferred = False s = SessionStore(SESSION_KEY) s.clear() s["item"] = item s.save() s = SessionStore(SESSION_KEY) s.modified = True s.save() i2 = s["item"] self.assertFalse(i2._deferred) # Regression for #11936 - loading.get_models should not return deferred # models by default. klasses = sorted(cache.get_models(cache.get_app("defer_regress")), key=lambda klass: klass.__name__) self.assertEqual(klasses, [Child, Item, Leaf, Proxy, RelatedItem, ResolveThis]) klasses = sorted( map(attrgetter("__name__"), cache.get_models(cache.get_app("defer_regress"), include_deferred=True)) ) self.assertEqual( klasses, [ "Child", "Child_Deferred_value", "Item", "Item_Deferred_name", "Item_Deferred_name_other_value_text", "Item_Deferred_name_other_value_value", "Item_Deferred_other_value_text_value", "Item_Deferred_text_value", "Leaf", "Leaf_Deferred_child_id_second_child_id_value", "Leaf_Deferred_name_value", "Leaf_Deferred_second_child_value", "Leaf_Deferred_value", "Proxy", "RelatedItem", "RelatedItem_Deferred_", "RelatedItem_Deferred_item_id", "ResolveThis", ], )
#pylint: disable-msg=W0212 import add_path # truqui para aƱadir los paths que nos interesan #IGNORE:W0611 import os # cargamos los settings del proyecto from django.core.management import setup_environ import settings setup_environ(settings) from django.db.models.loading import cache from optparse import OptionParser #cogemos los modelos de la aplicacion rtg con el orden como estan #definidos en models.py rtg_models=cache.get_models(cache.get_app('rtg')) rtg_models.reverse() parser = OptionParser() parser.add_option("-b", "--backup", action="store_true", dest="backup", default=False, help="hacer backup de las tablas") parser.add_option("-r", "--restore", action="store_true", dest="restore", default=False, help="hacer restore de las tablas") (options, dummy) = parser.parse_args() dtb = settings.DATABASES['default'] print "Trabajando con DB %s" % (dtb['NAME'])
A listing of code coverage by module. Name Stmts Exec Cover ----------------------------------------------------- scaffold.admin 375 258 68% scaffold.forms 8 7 87% scaffold.middleware 51 35 68% scaffold.models 87 82 94% scaffold.templatetags.sections 65 58 89% scaffold.views 19 9 47% ----------------------------------------------------- TOTAL 605 449 74% """ try: cache.get_app('admin') HAS_DJANGO_AUTH = True except ImproperlyConfigured: HAS_DJANGO_AUTH = False BASE_DATA = [ {'data':{'slug': '1', 'title': '1', 'description':'1'}}, {'data':{'slug': '2', 'title': '2', 'description':'2'}, 'children':[ {'data':{'slug': '21', 'title': '21', 'description':'21'}}, {'data':{'slug': '22', 'title': '22', 'description':'22'}}, {'data':{'slug': '23', 'title': '23', 'description':'23'}, 'children':[ {'data':{'slug': '231', 'title': '231', 'description':'231'}}, ]}, {'data':{'slug': '24', 'title': '24', 'description':''}}, ]}, {'data':{'slug': '3', 'title': '3', 'description':'3'}},
def _get_models(apps): ret = [] for app_label in apps or []: app = cache.get_app(app_label) ret += [m for m in cache.get_models(app)] return ret
def migrations_module(cls, app_label): if app_label in settings.MIGRATION_MODULES: return settings.MIGRATION_MODULES[app_label] app = cache.get_app(app_label) return ".".join(app.__name__.split(".")[:-1] + ["migrations"])
A listing of code coverage by module. Name Stmts Exec Cover ----------------------------------------------------- scaffold.admin 375 258 68% scaffold.forms 8 7 87% scaffold.middleware 51 35 68% scaffold.models 87 82 94% scaffold.templatetags.sections 65 58 89% scaffold.views 19 9 47% ----------------------------------------------------- TOTAL 605 449 74% """ try: cache.get_app('admin') HAS_DJANGO_AUTH = True except ImproperlyConfigured: HAS_DJANGO_AUTH = False BASE_DATA = [ { 'data': { 'slug': '1', 'title': '1', 'description': '1' } }, { 'data': { 'slug': '2',
def handle(self, *app_labels, **options): self.verbosity = int(options.get('verbosity')) self.interactive = options.get('interactive') self.dry_run = options.get('dry_run', False) self.merge = options.get('merge', False) # Make sure the app they asked for exists app_labels = set(app_labels) bad_app_labels = set() for app_label in app_labels: try: cache.get_app(app_label) except ImproperlyConfigured: bad_app_labels.add(app_label) if bad_app_labels: for app_label in bad_app_labels: self.stderr.write("App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label) sys.exit(2) # Load the current graph state. Takes a connection, but it's not used # (makemigrations doesn't look at the database state). loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() if conflicts and not self.merge: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError("Conflicting migrations detected (%s).\nTo fix them run 'python manage.py makemigrations --merge'" % name_str) # If they want to merge and there's nothing to merge, then politely exit if self.merge and not conflicts: self.stdout.write("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) # Detect changes autodetector = MigrationAutodetector( loader.graph.project_state(), ProjectState.from_app_cache(cache), InteractiveMigrationQuestioner(specified_apps=app_labels), ) changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None) # No changes? Tell them. if not changes and self.verbosity >= 1: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) elif len(app_labels) > 1: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") return directory_created = {} for app_label, migrations in changes.items(): if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") for migration in migrations: # Describe the migration writer = MigrationWriter(migration) if self.verbosity >= 1: self.stdout.write(" %s:\n" % (self.style.MIGRATE_LABEL(writer.filename),)) for operation in migration.operations: self.stdout.write(" - %s\n" % operation.describe()) # Write it if not self.dry_run: migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label, False): if not os.path.isdir(migrations_directory): os.mkdir(migrations_directory) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "wb") as fh: fh.write(migration_string)
def migrations_module(cls, app_label, migration_modules={}): if app_label in migration_modules: return migration_modules[app_label] app = cache.get_app(app_label) return ".".join(app.__name__.split(".")[:-1] + ["migrations"])
def test_basic(self): # Deferred fields should really be deferred and not accidentally use # the field's default value just because they aren't passed to __init__ Item.objects.create(name="first", value=42) obj = Item.objects.only("name", "other_value").get(name="first") # Accessing "name" doesn't trigger a new database query. Accessing # "value" or "text" should. with self.assertNumQueries(0): self.assertEqual(obj.name, "first") self.assertEqual(obj.other_value, 0) with self.assertNumQueries(1): self.assertEqual(obj.value, 42) with self.assertNumQueries(1): self.assertEqual(obj.text, "xyzzy") with self.assertNumQueries(0): self.assertEqual(obj.text, "xyzzy") # Regression test for #10695. Make sure different instances don't # inadvertently share data in the deferred descriptor objects. i = Item.objects.create(name="no I'm first", value=37) items = Item.objects.only("value").order_by("-value") self.assertEqual(items[0].name, "first") self.assertEqual(items[1].name, "no I'm first") RelatedItem.objects.create(item=i) r = RelatedItem.objects.defer("item").get() self.assertEqual(r.item_id, i.id) self.assertEqual(r.item, i) # Some further checks for select_related() and inherited model # behavior (regression for #10710). c1 = Child.objects.create(name="c1", value=42) c2 = Child.objects.create(name="c2", value=37) Leaf.objects.create(name="l1", child=c1, second_child=c2) obj = Leaf.objects.only("name", "child").select_related()[0] self.assertEqual(obj.child.name, "c1") self.assertQuerysetEqual( Leaf.objects.select_related().only("child__name", "second_child__name"), [ "l1", ], attrgetter("name")) # Models instances with deferred fields should still return the same # content types as their non-deferred versions (bug #10738). ctype = ContentType.objects.get_for_model c1 = ctype(Item.objects.all()[0]) c2 = ctype(Item.objects.defer("name")[0]) c3 = ctype(Item.objects.only("name")[0]) self.assertTrue(c1 is c2 is c3) # Regression for #10733 - only() can be used on a model with two # foreign keys. results = Leaf.objects.only("name", "child", "second_child").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") results = Leaf.objects.only("name", "child", "second_child", "child__name", "second_child__name").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") # Test for #12163 - Pickling error saving session with unsaved model # instances. SESSION_KEY = '2b1189a188b44ad18c35e1baac6ceead' item = Item() item._deferred = False s = SessionStore(SESSION_KEY) s.clear() s["item"] = item s.save() s = SessionStore(SESSION_KEY) s.modified = True s.save() i2 = s["item"] self.assertFalse(i2._deferred) # Regression for #11936 - loading.get_models should not return deferred # models by default. klasses = sorted(cache.get_models(cache.get_app("defer_regress")), key=lambda klass: klass.__name__) self.assertEqual(klasses, [ Child, Feature, Item, ItemAndSimpleItem, Leaf, Proxy, RelatedItem, ResolveThis, SimpleItem, SpecialFeature, ]) klasses = sorted( map( attrgetter("__name__"), cache.get_models(cache.get_app("defer_regress"), include_deferred=True), )) # FIXME: This is dependent on the order in which tests are run -- # this test case has to be the first, otherwise a LOT more classes # appear. self.assertEqual(klasses, [ "Child", "Child_Deferred_value", "Feature", "Item", "ItemAndSimpleItem", "Item_Deferred_name", "Item_Deferred_name_other_value_text", "Item_Deferred_name_other_value_value", "Item_Deferred_other_value_text_value", "Item_Deferred_text_value", "Leaf", "Leaf_Deferred_child_id_second_child_id_value", "Leaf_Deferred_name_value", "Leaf_Deferred_second_child_id_value", "Leaf_Deferred_value", "Proxy", "RelatedItem", "RelatedItem_Deferred_", "RelatedItem_Deferred_item_id", "ResolveThis", "SimpleItem", "SpecialFeature", ]) # Regression for #16409 - make sure defer() and only() work with annotate() self.assertIsInstance( list(SimpleItem.objects.annotate(Count('feature')).defer('name')), list) self.assertIsInstance( list(SimpleItem.objects.annotate(Count('feature')).only('name')), list)