Skip to content

Instantly share code, notes, and snippets.

@miceno
Created September 12, 2014 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miceno/fddb314144976c4f7356 to your computer and use it in GitHub Desktop.
Save miceno/fddb314144976c4f7356 to your computer and use it in GitHub Desktop.
A dictionary from a list of tuples
# List of selected categories
selected_categories = [Category.objects.get(name="TERRESTRE"), Category.objects.get(name="MOLUSCOS")]
# Products we want to filter based on the list of selected categories
products = Product.objects.filter(category__in = selected_categories)
# list is a tuple of tuples like ((id1, product_count1), (id2, product_count2), ... , (idn, product_countn))
qs_count = Category.objects.values(‘id’).filter(product__in=products).annotate(Count('product'))
# Get the values
list = qs_count.values_list('id', 'product__count') )
# Build the dictionary
d = dict( (key,value) for (key,value) in list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment