本文介绍了计数来自manytomanyfield的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一组具有多个字段的对象中计算不同的值。

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

例如

对象文章有多个标签对象的

object article has manytomanyfield of tag objects

一篇文章有​​标签tag1tag2

one article has tags "tag1" "tag2"

另一篇文章有​​标签tag2tag3

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

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

我以为我可以用articles.objects.all()。values('tags')或某些东西做某事,但是我出来了。

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

推荐答案

models.py



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)

.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

这篇关于计数来自manytomanyfield的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 14:11