[Answer]-Django prefetch_related on many to many field always yields empty array

1👍

Yikes. Figured out the problem. Some time ago there was a bug where prefetch_related wouldn’t work if your model’s pk field was non-text (like an integer). I manually patched this line:

vals = rel_obj_cache.get(instance_attr_val, [])

near the end of query.py to look like this:

vals = rel_obj_cache.get(unicode(instance_attr_val), [])

That fixed my problem. But since then I guess the problem was solved formally in another way and now my unicode cast was causing that dictionary lookup to return an empty list (basically the reverse of the original bug).

So, just had to undo my manual patch and now it works fine. No wonder I couldn’t find anyone else having this problem!

👤Dustin

Leave a comment