从manytomanyfield计算值

时间:2010-12-25 01:07:46

标签: django manytomanyfield

我试图从一组具有manytomanyfield

的对象中计算不同的值

e.g。

对象文章有许多标记对象的字段


一篇文章标签为“tag1”“tag2”

另一篇文章标签为“tag2”“tag3”


我想找出一些可以返回的内容:

“tag1”:1 “tag2”:2 “tag3”:1

我以为我可以用articles.objects.all()。values('tags')或者其他东西做些什么,但我空洞了。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

您的问题是相关的: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()