This appears to be a new feature. Is there any way of doing this in 1.0? Other than dropping into SQL that is.
Graeme On Jun 17, 8:04 pm, Alex Gaynor <alex.gay...@gmail.com> wrote: > On Wed, Jun 17, 2009 at 10:00 AM, R C <rileycr...@gmail.com> wrote: > > > Thanks for your fast reply.... > > > I realize that there is no "count" field in my article model. However > > in my templates I am able to do things like: > > Author.article_set.count > > > I just can't do the same thing in my views when building a > > queryset.....I would really like to be able to select Authors and > > order them by the number of Articles they have written. Any ideas on > > how to accomplish this? > > > One could accomplish this with SQL as follows: > > select author_id, count(author_id) from article_table group by > > author_id; > > > This would return something like > > author_id | count(author_id) > > 1 10 > > 2 20 > > 3 30 > > > On Jun 17, 3:47 pm, Daniel Roseman <dan...@roseman.org.uk> wrote: > > > On Jun 17, 1:12 pm, R C <rileycr...@gmail.com> wrote: > > > > > Hi, > > > > > I would like to be able to select objects and order them by the count > > > > of a related field > > > > > For example, I have 2 models: > > > > > class Author(models.Model) > > > > name = models.Charfield(max_length=20) > > > > > class Article(models.Model) > > > > author = models.ForeignKey(Author) > > > > content = models.TextField() > > > > > Let's say I have 3 authors: > > > > 1) John -- has 10 articles > > > > 2) Bob -- has 20 articles > > > > 3) Lisa -- has 30 articles > > > > > I would like to select authors and order by the number of articles > > > > they have written: > > > > Author.objects.all().order_by('article__count') > > > > > But this does not work. > > > > No, because you don't have a 'count' field in your article model. > > > > Read this (SVN version only): > >http://docs.djangoproject.com/en/dev/topics/db/aggregation/ > > > -- > > > DR. > > That's why Daniel linked the aggregates documentation, which allows queries > such as the one you suggested to be preformed: > > Author.objects.annotate(c=Count('article')).oder_by('c') > > Alex > > -- > "I disapprove of what you say, but I will defend to the death your right to > say it." --Voltaire > "The people's good is the highest law."--Cicero --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---