On Fri, 2009-03-20 at 03:01 -0700, Jamie Pittock wrote:
> Hi all,
> 
> I have two models, Provider and Record.  Record has the foreign key
> provider_id.  In my template I'm displaying how many records a
> provider has by using object.record__set.count.  If Record had a
> status field, how would I display how many records with a particular
> status a provider had?

You can't do this directly in the template, since it requires a
semi-complex queryset operation. You also can't do it easily in Django
1.0.x, since that would require writing raw SQL to do the grouping and
counting.

In Django 1.1-alpha, a solution would look something like the following:

        providers = Provider.objects.filter(...) # Your normal queryset
        status_counts = Record.objects.filter(record__in=providers). \
                  values("status", "provider").annotate(num=Count("id")). \
                  order_by()
        
The empty order_by() call at the end is to avoid bug #10574 for the
moment.

The second line here should return you a list of dictionaries with each
dictionary looking like

        {"status": 43, "provider": 11, "num": 17}
        
You then have something you can either merge with the provider objects
in the view (assigning each dictionary to an attribute on the provider
object that matches the "provider" key), or use some other way in the
template directly. What I've shown you here is how to compute the data
you want in a single SQL query.

If you're stuck as to how to whack it together for use in a template,
sing out, but hopfefully this gives you something to start with.

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to