Preface: No nonsense. directly into the body
Body:
How do I use distinct to query multiple distinct record values in MySQL?
First, we have to know that there are two ways to execute a query in a Django model:
The first is to use a Django-given API, such as a model query API such as the filter value distinct order_by.
Code: LOrder.objects.values (' finish_time '). Distinct ()
It should be noted here that the original official document reads:
Example (the first example will only work on PostgreSQL):
>>>Author.Objects.distinct()[...]>>>Entry.Objects.Order_by(' Pub_date ').Distinct(' Pub_date ')[...]>>>Entry.Objects.Order_by(' Blog ').Distinct(' Blog ')[...]>>>Entry.Objects.Order_by(' Author ',' Pub_date ').Distinct(' Author ',' Pub_date ')[...]>>> entry. Objects. Order_by ( ' blog__name ' ' mod_date ' ) . Distinct ( ' blog__name ' ' mod_date ' ) [...] >>> entry. Objects. Order_by ( ' author ' ' pub_date ' distinct ( ' author ' )
Because I use the MySQL database, the distinct can only be used in the first use, or it can be
LOrder.objects.values (' Finish_time '). Distinct (). order_by (' Finish_time ')
Second, use the original SQL query
LOrder.objects.raw (' SELECT DISTINCT id,finish_time from Keywork_lorder Group by Finish_time ')
The above directly uses the MySQL statement to tick, here need to pay special attention to:
One is that there is only one field in the original SQL query that cannot be discarded, as the official document says:
only one field can not be omitted--that is, the primary key. Django uses a primary key to identify instances of the model, so it must be included in each of the original queries. If you forget to include the primary key, a invalidquery exception is thrown .
This means that if your SQL statement is such a ' SELECT DISTINCT finish_time from Keywork_lorder ', then the error will be the raw query must include the primary key, which is the ID field cannot be Get lost!
Second, here is the original MySQL query statement, MySQL removed duplicates to write: ' SELECT DISTINCT id,finish_time from Keywork_lorder Group by Finish_time '
[Django/mysql] A solution for querying multiple distinct record values in MySQL using distinct