[CentralOH] Counting References in Django

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Fri Dec 7 01:43:23 CET 2012

In Django, what's a better way of counting references to a record 
of an arbitrary model than my following working code? 

    c = 0
    for r in record._meta.get_all_related_objects():
        c += r.model.objects.filter(
            **{r.field.name + '__exact': record.id}).count()

I can rearrange that into a single statement as follows, 
but it's harder to read, so that's not better. 

    c = sum(map(
        (lambda r: r.model.objects.filter(
        **{r.field.name + '__exact': record.id}).count()),

More information about the CentralOH mailing list