我很惊讶这个问题没有出现.在网上找不到多少.
使用Entry.objects.latest('created_at')我可以恢复所有Entry对象的最新条目,但是如果我想要每个用户的最新条目?这类似于SQL最新记录查询.但是我如何使用ORM实现这一目标?这是我的方法,我想知道它是否是最有效的方式来做我想要的.
首先,我执行子查询:对象按用户分组,并为每个用户返回Max(最新)created_by字段(created_at__max)然后根据子查询中的结果过滤Entry对象并获取所需对象.
Entry.objects.filter(created_at__in=Entry.objects.values('user').annotate(Max('created_at')).values_list('created_at__max'))
Run Code Online (Sandbox Code Playgroud)
或使用经理:
class UsersLatest(models.Manager):
def get_query_set(self):
return super(UsersLatest,self).get_query_set().filter(created_at__in=self.model.objects.values('user').annotate(Max('created_at')).values_list('created_at__max'))
Run Code Online (Sandbox Code Playgroud)
有更有效的方法吗?可能没有子查询?
谢谢,
保罗
Entry.objects.all().order_by('user', 'created_at').distinct('user')
Run Code Online (Sandbox Code Playgroud)
然后为了提高性能,在 'user' 和 'created_at' 字段上添加索引。
但我认为真正的生产方式是用于Redis缓存和更新用户最新条目的 id 列表。
| 归档时间: |
|
| 查看次数: |
2978 次 |
| 最近记录: |