简体   繁体   中英

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.

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. 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. There could be 5-10 Model instances with the same name but I only want to pass one to avoid having duplicates.

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. 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?

Model.objects.values('name').all().distinct()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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