I don't understand from your description what you're actually doing, but
it sounds a lot like you're trying to read from the same QuerySet in
multiple threads whilst it's still retrieving results from the database
cursor. Don't do that. Firstly, database cursor result sets aren't
necesarily safe to be shared across threads. QuerySet and Query objects
probably are once the result set is populated, since every non-trivial
operation on them creates a copy and parallel iteration is supported,
but that's more by accident than design, since it's not worth the extra
overhead: if you want to share QuerySets via caching, they contain the
results (the result_cache is already fully primed).
Nothing in Django will cache a connection to the database or a cursor
result set, so can you break down your problem a bit more to describe
where the simultaneous access is happing. You say "the usual
ValueError", but I have never seen that raised by anything in Django. So
I'm wondering if you're doing something fairly unusual here.
That particular block of code is *designed* to be used in parallel
iterators in the same thread, so it's safe in that respect. But if
you're sharing a partially-read database cursor iterator across multiple
threads, it might be a case of it breaks you get to keep all the pieces.
I can't see why that would be necessary (if you want to cache the
results, just cache the queryset and it will cache the results; if you
want to cache the query, cache queryset.query and it will just cache the
query; both of those cases are designed in and documented).
Regards,
Malcolm