How to query as GROUP BY in django?

前端 未结 9 1269
别跟我提以往
别跟我提以往 2020-11-22 05:40

I query a model:

Members.objects.all()

And it returns:

Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2         


        
9条回答
  •  遇见更好的自我
    2020-11-22 06:09

    The document says that you can use values to group the queryset .

    class Travel(models.Model):
        interest = models.ForeignKey(Interest)
        user = models.ForeignKey(User)
        time = models.DateTimeField(auto_now_add=True)
    
    # Find the travel and group by the interest:
    
    >>> Travel.objects.values('interest').annotate(Count('user'))
    
    # the interest(id=5) had been visited for 2 times, 
    # and the interest(id=6) had only been visited for 1 time.
    
    >>> Travel.objects.values('interest').annotate(Count('user', distinct=True)) 
    
    # the interest(id=5) had been visited by only one person (but this person had 
    #  visited the interest for 2 times
    

    You can find all the books and group them by name using this code:

    Book.objects.values('name').annotate(Count('id')).order_by() # ensure you add the order_by()
    

    You can watch some cheet sheet here.

提交回复
热议问题