Created
June 25, 2014 16:36
-
-
Save evilchili/fba18d254890ad7b5bf9 to your computer and use it in GitHub Desktop.
unique values from a django model field containing CSVs
This file contains hidden or 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
from django.db import models | |
class Record(models.Model): | |
types = models.CharField(db_index=True) | |
# ... some other stuff ... | |
@classmethod | |
def distinct_types(cls): | |
""" | |
Return a list of unique types from all Records | |
""" | |
# all_types is a list of tuples, possibly containing CSVs | |
all_types = cls.objects.order_by().values_list('types').distinct() | |
# convert each tuple to a list, and reduce them into a single set of unique values | |
all_types = reduce(lambda x, y: list(x) + list(y), all_types) | |
# split all members of the set on ',' and reduce the expanded lists back into a set, | |
# filtering out NULLs along the way. | |
return set(reduce(lambda x, y: x + y, [t.split(',') for t in all_types if t is not None])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a more efficient way to do this?