Skip to content

Instantly share code, notes, and snippets.

@evilchili
Created June 25, 2014 16:36
Show Gist options
  • Save evilchili/fba18d254890ad7b5bf9 to your computer and use it in GitHub Desktop.
Save evilchili/fba18d254890ad7b5bf9 to your computer and use it in GitHub Desktop.
unique values from a django model field containing CSVs
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]))
@evilchili
Copy link
Author

Is there a more efficient way to do this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment