Simon proposed [0]: "I wonder if we should prevent django.db from executing queries until django.apps.apps.ready or at least issue a RuntimeWarning. We would have to go through deprecation but I'm pretty sure this would uncover a lot of existing application bugs and prevent future ones. This is related to #25454 <https://code.djangoproject.com/ticket/25454> [1] and probably a large number of closed tickets."
We have this restriction in some places, for example: "Executing database queries with the ORM at import time in models modules will also trigger this exception. The ORM cannot function properly until all models are available." We also have a warning about using the ORM in AppConfig.ready(): "Although you can access model classes as described above, avoid interacting with the database in your ready() implementation. This includes model methods that execute queries (save(), delete(), manager methods etc.), and also raw SQL queries via django.db.connection. Your ready() method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings, manage.py test would still execute some queries against your *production* database!" There's also a warning in the testing docs: "Finding data from your production database when running tests? If your code attempts to access the database when its modules are compiled, this will occur *before* the test database is set up, with potentially unexpected results. For example, if you have a database query in module-level code and a real database exists, production data could pollute your tests. *It is a bad idea to have such import-time database queries in your code* anyway - rewrite your code so that it doesn’t do this. This also applies to customized implementations of ready()." What do you think? Prohibiting such queries might be too strict at this point as I guess some users might rely on them. I suppose warnings could be selectively silenced as/if needed. We could start with a warning and ask users to let us know if they believe they have a legitimate usage. If we don't hear anything, we could proceed with the deprecation. Related tickets: [0] https://code.djangoproject.com/ticket/26273 [1] https://code.djangoproject.com/ticket/25454 -- You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscr...@googlegroups.com. To post to this group, send email to django-developers@googlegroups.com. Visit this group at https://groups.google.com/group/django-developers. To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/7f41ba58-09ed-4f78-b5ce-be6d7d5a6fc7%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.