Greetings, For a couple of things I’ve been working on, I wound up hitting exactly the same problem with respect to SQL generation.
It seems that the `FROM` clauses are generated after the SELECT, but before WHERE. This means that any .as_sql() code that is run only on things that appear in a WHERE clause but not in a SELECT clause can reference any of the aliases that it needs to generate it’s SQL, but is not able to “ref” the alias (ie, indicate that it has actually used it). This means that there are certain situations where a table is referenced but the SQL compiler does not know about that reference, and the table is stripped out. I have a fairly simple PR, that is passing tests, to move the FROM generation until after any WHERE clauses have been executed. https://github.com/django/django/pull/14683 Does anyone have any suggestions as to why the FROM needs to be generated before the WHERE? For background the things I’ve hit this same issue in are: Django Implied Relationship <https://schinckel.net/2021/07/14/django-implied-relationship/> - creating implicit relationships between objects that don’t otherwise have a direct relationship https://github.com/schinckel/django-shared-property <https://github.com/schinckel/django-shared-property> - which is woefully under-documented, but basically allows defining an expression as something that should (a) always be annotated onto a query, but (b) also be “live”, and changes to the dependencies affect the value the property returns. https://github.com/schinckel/django-shared-property/blob/main/tests/models.py <https://github.com/schinckel/django-shared-property/blob/main/tests/models.py> has some nice examples. Cheers, Matt. -- 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 view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/9F101363-110C-498A-8C6C-554138F8D673%40schinckel.net.