4

I am trying to make a Django query for getting a list of the last entries for each distinct values from a MySQL database. I will show an example below as this explanation can be very complicated. Getting the distinct values by themselves obviously in Django is no problem using .values(). I was thinking to create couple of Django queries but that looks to be cumbersome. Is there an easy way of doing this.

For the example below. Suppose I want the rows with distinct Names with their last entry(latest date).

Name            email                 date
_________________________________________________

Dane            [email protected]        2017-06-20
Kim             [email protected]         2017-06-10
Hong            [email protected]        2016-06-25
Dane            [email protected]        2017-06-04
Susan           [email protected]       2017-05-21
Dane            [email protected]        2017-02-01
Susan           [email protected]         2017-05-20

All the distinct values are Dane, kim, Hong, Susan. I also want the rows with the latest dates associated with these distinct name. The list with entries I would like is the rows below. Notice Names are all distinct, and they are associated with the latest date.

 Name            email                 date
_________________________________________________

Dane            [email protected]        2017-06-20
Kim             [email protected]         2017-06-10
Hong            [email protected]        2016-06-25
Susan           [email protected]       2017-05-21
Jam1
  • 629
  • 12
  • 25

3 Answers3

2

with postgresql you should able to do:

 EmailModel.objects.all().order_by('date').distinct('Name')

for more methods/functions like this, you can visit the docs here

Dimas Ari
  • 148
  • 1
  • 8
1

This only applies to POSTGRES

You can use the ORDER_BY command to set your query set as ordered by date, then chain with the DISTINCT command to get distinct rows and specify which field. The DISTINCT command will take the first entry for each name. Refer The Docs For More

Edit

For MYSQL, you will have to use raw SQL queries, refer here

pypypy
  • 1,075
  • 8
  • 18
  • Thank you sir, but I am using `MySQL`. I will keep playing around with it. Come to think of it I was using `order_by` and ran into some command line problem on the `Python` console – Jam1 Jun 21 '17 at 01:25
1

Only Postgres supports providing field names in distinct. Also, any field provided in values and order_by is in distinct, thus providing ambiguous results sometimes.

However for MySQL:

Model.objects.values('names').distinct().latest('date')
Raj Subit
  • 1,487
  • 2
  • 12
  • 23