Search code examples
djangocountuniquemodels

Counting database entries by field type in django


I have a model in my django project called "change" and it has a field called "change_type". There are multiple values within the change_type field to include "move", "new", "edit" and others with new types being added randomly over any given period of time. I am currently using normal django queries to select groups of entries within the change model.

Is there a quick method to determine what unique entries are in the change_type field? Is there a quick method to return a count of each entry type?


Solution

  • Putting it together:

     occurrences = {}
     change_types = Change.objects.values_list('change_type', flat=True).distinct()
    
     for type in change_types:
         occurrences[type] = Change.objects.filter(change_type=type).count()