count values from manytomanyfield

前端 未结 2 1682
無奈伤痛
無奈伤痛 2021-01-20 15:27

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


相关标签:
2条回答
  • 2021-01-20 16:04

    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()
    
    0 讨论(0)
  • 2021-01-20 16:07

    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
    
    0 讨论(0)
提交回复
热议问题