code: def count_unique(table, field=-1):
      
      from collections import Counter
  
      # try/except only happens once, and fastest route (straight to db) tried first
      try:
          ans = {}
          for row in table.distinct().values(field).annotate(field_value_count=models.Count(field)):
              ans[row[field]] = row['field_value_count']
          return ans
      except:
          try:
              return Counter(row[field] for row in table)
          except:
              try:
                  return Counter(row.get(field, None) for row in table)
              except:
                  try:
                      return Counter(row.getattr(field, None) for row in table)
                  except:
                      pass
docs: Use the Django ORM or collections.Counter to count unique values of a field in a table
  
      `table` is one of:
      1. An iterable of Django model instances for a database table (e.g. a Django queryset)
      2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string
      3. An iterable of objects or namedtuples with elements accessed by `row.field`
  
      `field` can be any immutable object (the key or index in a row of the table that access the value to be counted)