Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Created July 7, 2015 15:28
Show Gist options
  • Save kezabelle/90ce60ce31e328fe094b to your computer and use it in GitHub Desktop.
Save kezabelle/90ce60ce31e328fe094b to your computer and use it in GitHub Desktop.
for the_drow in #django IRC. I can't remember whether any() will bail at the first `True`, which would presumably be the quickest exit.
class MyThing(Model):
def has_value_x_y(self):
assert hasattr(self, '_prefetched_objects_cache'), \
"needs prefetch_related()"
# `my_thing__set` becomes `my_thing` in the prefetch cache ...
assert 'RELATION' in self._prefetched_objects_cache, \
"needs prefetch_related('RELATION_set')"
count = (True for x in self.RELATION_set.all())
return any(count)
# will be an AssertionError to remind you not to cross relations without doing the right thing
MyThing.objects.all()[0].has_value_x_y()
# this will be fine, but will do all the work to get all the results. Useful if mostly you want
# to act on the related data afterwards anyway.
MyThing.objects.prefetch_related('RELATION_set')[0].has_value_x_y()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment