count values from manytomanyfield
Asked Answered
C

2

5

I am trying to count the distinct values from a group of objects that have a manytomanyfield

e.g.

object article has manytomanyfield of tag objects


one article has tags "tag1" "tag2"

another article has tags "tag2" "tag3"


I would like to figure out something that would return something along the lines of:

"tag1": 1 "tag2": 2 "tag3": 1

I thought I could do something with articles.objects.all().values('tags') or something but I came up empty.

Coriolanus answered 25/12, 2010 at 1:7 Comment(1)
I found a way by doing Tag.objects.filter(article__in=articles).values('name').annotate(count=Count("pk")) but this seems really computationally intense.Coriolanus
N
9

models.py

class Topping(models.Model):
        name = models.CharField(max_length = 20)

class Pizza(models.Model):
        name = models.CharField(max_length = 20)
        toppings = models.ManyToManyField(Topping)

python manage.py shell

>>> from many_to_many.models import Pizza, Topping
>>> t1 = Topping(name = "T1")
>>> t2 = Topping(name = "T2")
>>> t3 = Topping(name = "T3")
>>> t4 = Topping(name = "T4")
>>> p1 = Pizza(name="P1")
>>> p2 = Pizza(name="P2")


>>> p1.toppings.add(t1)
>>> p1.toppings.add(t2)
>>> p2.toppings.add(t2)
>>> p2.toppings.add(t3)


>>> t2.pizza_set.count() 
    2
>>> t1.pizza_set.count() 
    1
Nymphomania answered 27/12, 2010 at 11:15 Comment(0)
C
4

You question is related: How to count and display objects in relation ManyToMany in Django

models.py

class Topping(models.Model):
        name = models.CharField(max_length = 20)

class Pizza(models.Model):
        name = models.CharField(max_length = 20)
        toppings = models.ManyToManyField(Topping)

python manage.py shell

>>> for topping in Topping.objects.all():
...     print topping.name, topping.pizza_set.count()
Circlet answered 29/8, 2013 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.