django-ORM aggregate functions

The model structure models.py

# - * - Coding: UTF-8 - * - 
from django.db Import Models 

class Author (models.Model):
     " On model " 
    name = models.CharField (max_length = 100 ) 
    Age = models.IntegerField () 
    Email = Models .EmailField () 

    class Meta:                  # the name can not be changed 
        db_table = ' author '      # mapped to a custom database for your name, do not set this as the default package name is mapped to a database table names _ 


class Publisher (models.Model):
     " Publishing model " 
    name= models.CharField(max_length=300)

    class Meta:
        db_table = 'publisher'

class Book(models.Model):
    "book模型"
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.FloatField()
    rating = models.FloatField()
    author = models.ForeignKey(Author,on_delete = models.CASCADE)
    publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)

    class Meta:
        db_table = 'book'


class BookOrder(models.Model):
    "图书订单模型"
    book = models.ForeignKey("Book",on_delete=models.CASCADE)
    price = models.FloatField()

    class Meta:
        db_table = 'book_order'

Aggregate function

In the views.py

1.Avg: Averaging

from django.shortcuts Import the render 

from django.http Import HttpResponse
 from .models Import Book
 from django.db.models Import Avg
 from django.db Import Connection 

DEF index (Request): 

    # Price (price field) Gets book under the table averaging value (average value) 
    Result = Book.objects.aggregate (Avg. ( ' . price ' ))   # Avg. can not be used directly, it is necessary to use aggregate wrap 
    Print (Result)
     Print (connection.queries)     #Can be translated into view sql statement, we need to import connection, if it is queryset, then you can use the query query 
    return HttpResponse ( ' index ' )

This time django will automatically give you create an alias, which is the field name __Avg, if you want to change, then more

    # This time django will automatically give you create an alias, which is the field name __Avg, if you want to change, then more 
    the Result = Book.objects.aggregate (price_avg = Avg ( ' . Price ' ))   # Avg can not be used directly, You need to use aggregate wrap

 

A method performed on aggregate, and the aggregate function annotate

Example: In the example, averaging
 # All values are the average value will 1.aggregate (connection modules need to import) 

DEF index (Request): 
Result = Book.objects (Avg. ( ' . Price ' ))   # Avg. Not directly use, we need to see the details of the wording aggregate wrap 1
Print (Result) # 2.annotate will then an additional group by grouping operation, and then obtaining an average value of each group  # find the average value of each group  # , then the tables associated with the Book BookOrder (using default on django lowercase) is disposed in the price field depending on the group id, and then the average value of each group 
Books = Book.objects.annotata (price_avg Avg. = ( ' bookorder__price ' )) # the name changed price_avg
for Book in Books: Print ( ' % S /% S ' % (book.name, book.price_avg)) # price_avg in front of the name has been changed, or is the default Avg

 Count ask each table how many id (that is seeking total)

from django.http Import HttpResponse
 from .models Import Book, Author, BookOrder
 from django.db.models Import Avg, the Count
 from django.db Import Connection 

    # 1. seeking the Count the number of each table id (which is seeking a total number) 
    # Result = Book.objects.aggregate (book_nums the Count = ( 'ID')) #book_nums custom key parameter, the user receives the returned data 
    # Print (Result) 
    # Print (connection.queries) # View converted into sql statement 

    # have at 2. the statistics Author table how many different mailboxes (that is, using only count when a statistical count the same mailbox, but not all statistics) - that is, = True dISTINCT 
    #result = Author.objects.aggregate (email_nums = Count ( 'email', distinct = True)) #email_nums custom key parameter, the user receives the returned data 
    # Print (Result) 
    # Print (connection.queries) # View converted into sql statement 

    # 3. DETAILED annotate to count the number of each of the packets (in other words is required for each volume group or the like can be used so this method) 
    Books = Book.objects.annotate (book_nums the count = ( ' bookorder__id ' ))    # bookorder__id i.e. under bookorder table id field 
    for Book in Books:
         Print ( ' % S / S% ' % (book.name, book.book_nums))    # used book_nums custom parameter then this table is automatically increase this property

Max and Min Gets the specified object (a field) maximum and minimum values

from django.db.models Import Avg., the Count, Max, Min 

    # 1. Max and Min Gets the specified object (a field) maximum and minimum values 
    Result = Author.objects.aggregate (max = Max ( ' SGE ' ), min = min ( ' Age ' )) # find the maximum and minimum values, max and min in the age field Author table is customized for receiving values 
    Print (Request)
     Print (connection.queries) 

# Similarly packet may be used annogate seeking the maximum and minimum of each book

Sum: find the sum of a field

from .models Import Book, Author, BookOrder
 from django.db.models Import Avg, the Count, Max, Min, Sum
 # If a leak in the self-import, this is just a rough example 

    # 1 seeking total sales of all books, but also is the sum of all the books sold 
    # Result = BookOrder.objects.aggregate (= the sum Total ( 'price')) # obtains the price field BookOrder sum table 
    # Print (Request) 
    # Print (connection.queries) 

    # 2 . individually calculated for total sales of each book (that is, about the Three Kingdoms Dream of Red Mansions book and each book are how much to sell) - packet is required to Annotate 
    Books = BookOrder.objects.annotate (total = Sum ( ' bookorder__id ' ))     # of bookorder__id this field to make a packet, and then calculated the total amount of each packet, and then use a custom total reception 
    for Book inBooks:
         Print ( ' % S% S ' % (book.name, book.total))     # This total is the above-defined, custom will be good for the thickness of the attribute added to the table 
    Print (connection.queries) 

    # 3. the total sales in a given year seeking - here only to provide ideas 
    # ① first before acquiring a given year review of the data table name .objects.filter time query 
    # ② can then seek out these data using Sum, using normal and the aggregate Sum 


    # 4. requirements of each book in total sales in a given year, that is, the Three Kingdoms in 2018 sold a total of how much money Dream of Red Mansions in 2015 sold a total of how much money 
    # ① to get a year of data before the table name .objects.filter review time query 
    # ② and then based on these data using the Sum can find out, using normal annotate and Sum

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/ifdashui/p/11914776.html