Created
February 19, 2011 21:16
-
-
Save RobCombs/835375 to your computer and use it in GitHub Desktop.
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
def get_toplevel_categories(self, **filters): | |
""" | |
Similar to objects.filter but returns only toplevel results. | |
Example: | |
Category.objects.get_toplevel_categories(categorysubset__sites__exact=settings.SITE_ID) | |
""" | |
#Filter categories based on the filter keyword argument | |
category_subset = self.filter(**filters) | |
#Now let's fetch their corresponding parents and intersections | |
top_level_categories = category_subset.filter(models.Q(parent=None) | ~models.Q(parent__in=category_subset)).distinct() | |
#If there are no top level categories, it's most likely because subsets have not been set up yet, | |
#in which case we want all of top level categories. This will prevent the primary_category field from showing up blank | |
#for unit tests and when there are not subsets defined. | |
if top_level_categories.count()==0: | |
top_level_categories = self.filter(parent=None) | |
return top_level_categories |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment