Created
April 20, 2015 08:12
-
-
Save kezabelle/1eb7940431ea948ca3fd to your computer and use it in GitHub Desktop.
Is there a better way of handling sometimes prefetched data in Django models than this?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyRelation(models.Model): | |
""" | |
This simple example demonstrates the fat model which needs some related data, | |
but obviously can't know [without introspecting as I'm doing here] whether or | |
not it needs to eagerly fetch the data, or whether it can just enumerate | |
the prefetch results. | |
""" | |
def prefetched_active_users(self): | |
# assumes .prefetch_related('users') has happened. | |
return tuple(x for x in self.users.all() if x.is_active is True) | |
def active_users(self): | |
if hasattr(self, '_prefetched_objects_cache'): | |
if 'users' in self._prefetched_objects_cache: | |
return self.prefetched_active_users() | |
return tuple(self.users.filter(is_active=True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment