Django查询:按列表获取所有不同值的最后一个条目 [英] Django query: get the last entries of all distinct values by list
问题描述
我正在尝试进行Django查询,以从 MySQL
数据库获取每个不同值的最后一个条目的列表。我将在下面显示一个示例,因为这种解释可能非常复杂。使用 .values()
显然可以在Django中单独获取不同的值。我当时在考虑创建几个Django查询,但这看起来很麻烦。有没有简便的方法。
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 dane@yahoo.com 2017-06-20
Kim kim@gmail.com 2017-06-10
Hong hong@gmail.com 2016-06-25
Dane dddd@gmail.com 2017-06-04
Susan Susan@gmail.com 2017-05-21
Dane kkkk@gmail.com 2017-02-01
Susan sss@gmail.com 2017-05-20
所有不同的值是Dane,kim,Hong和Susan。我还希望这些最新名称与这些唯一名称相关联的行。我想要的条目列表是下面的行。通知名称都是不同的,并且它们与最新日期相关。
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 dane@yahoo.com 2017-06-20
Kim kim@gmail.com 2017-06-10
Hong hong@gmail.com 2016-06-25
Susan Susan@gmail.com 2017-05-21
推荐答案
使用postgresql,您应该能够做到:
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
这篇关于Django查询:按列表获取所有不同值的最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!