-
Notifications
You must be signed in to change notification settings - Fork 130
Description
This is an issue that of course also exists in the ESSolution library that this repo is forked from.
When using prefetch_related to optimize queries for many-to-one and many-to-many relationships, Django generates an IN clause containing all of the primary keys that a M:1 model's foreign key should be filtered on, thus solving the N+1 problem.
However, MS SQL Server has a 2100 parameter limit, which causes the rdbms to fail when trying to prefetch objects with more than 2100 possible foreign keys. It would be awesome if the driver could add support for handling this stark limitation.
The official MS SQL Server IN clause documentation recommends creating a temp table and then joining over that. Without being too familiar with Django ORM internals, I don't know how feasible it would be to override the prefetch_related as_sql query to implement this solution.
There is a related issue in the ESSolutions/django-mssql-backend repo, where a suggested workaround is to override Django's In lookup class to basically pass in a single giant parameter string and then have SQL Server split it via {lhs} IN ( SELECT * FROM STRING_SPLIT(CONVERT(nvarchar(max), %s),',')))
. While this seems to work when filtering a queryset explicitly with __in
, the overridden lookup class is not used for prefetch_related calls.
A committed solution would be awesome, but I'd also love any advice you may have as a temporary workaround.