Django:独特的外键 [英] Django: Distinct foreign keys

查看:111
本文介绍了Django:独特的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Log:
project = ForeignKey(Project)
msg = CharField(...)
date = DateField(...)

我想选择四个最新的日志条目,其中每个日志条目必须有一个唯一的项目外键。我已经尝试了谷歌搜索的解决方案,但没有一个工作,django文档不是很好的查找..



我尝试了像: p>

  Log.objects.all()。distinct('project')[:4] 
Log.objects.values 'project')。distinct()[:4]
Log.objects.values_list('project')。distinct('project')[:4]
pre>

但是这不会返回同一个项目的任何内容或日志条目。



任何帮助将不胜感激

解决方案

查询不能像Django的ORM或底层SQL那样工作。如果要获取唯一的ID,则只能查询ID。所以你需要做两个查询来获取实际的日志条目。如下所示:

  id_list = Log.objects.order_by(' -  date')。values_list('project_id')。distinct )[:4] 
entries = Log.objects.filter(id__in = id_list)


class Log:
 project = ForeignKey(Project)
 msg = CharField(...)
 date = DateField(...)

I want to select the four most recent Log entries where each Log entry must have a unique project foreign key. I've tries the solutions on google search but none of them works and the django documentation isn't that very good for lookup..

I tried stuff like:

Log.objects.all().distinct('project')[:4]
Log.objects.values('project').distinct()[:4]
Log.objects.values_list('project').distinct('project')[:4]

But this either return nothing or Log entries of the same project..

Any help would be appreciated!

解决方案

Queries don't work like that - either in Django's ORM or in the underlying SQL. If you want to get unique IDs, you can only query for the ID. So you'll need to do two queries to get the actual Log entries. Something like:

id_list = Log.objects.order_by('-date').values_list('project_id').distinct()[:4]
entries = Log.objects.filter(id__in=id_list)

这篇关于Django:独特的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆