简体   繁体   English

如何在Django 1.1中执行“分组依据”查询?

[英]How to perform a “Group By” query in Django 1.1?

I have seen a lot of talk about 1.1's aggregation, but I am not sure how to use it to perform a simple group by. 我已经看过很多关于1.1聚合的讨论,但我不知道如何使用它来执行一个简单的组。

I am trying to use Django's sitemap framework to create a sitemap.xml file that Google can crawl to find all the pages of my site. 我正在尝试使用Django的站点地图框架来创建一个sitemap.xml文件,Google可以抓取该文件来查找我站点的所有页面。 Currently I am passing it all the objects, as in Model.objects.all() - however all that really matters is that only 1 per name gets passed. 目前我传递所有对象,如在Model.objects.all() - 但是真正重要的是每个名称只传递1个。 There could be 5-10 Model instances with the same name but I only want to pass one to avoid having duplicates. 可能有5-10个具有相同名称的Model实例,但我只想传递一个以避免重复。

If I do something like this: 如果我做这样的事情:

Model.objects.values('name').annotate(Count('name'))

It gives me what I want, but then I am not retrieving all the fields from the model - the code that creates the sitemap would then be forced to re-query for every single Model to create the link. 它给了我想要的东西,但后来我没有从模型中检索所有字段 - 然后,创建站点地图的代码将被强制重新查询每个模型以创建链接。 So how do I get it to group by the name while retrieving all the fields of the model? 那么在检索模型的所有字段时如何通过名称对其进行分组?

Django models are lazy loaded. Django模型是延迟加载的。 It will be the same amount of overhead if your code walks across your model relationships as if the sitemap did. 如果您的代码遍历模型关系,就像站点地图一样,这将是相同的开销。 The models fields are essentially proxies until you request related models. 在您请求相关模型之前,模型字段基本上是代理。

May be Distinct will help you? 可能是Distinct会帮助你吗?

Model.objects.values('name').all().distinct() Model.objects.values( '名')。所有()。不同的()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM