[CentralOH] Reinventing the Wheel: Counting References in Django

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Sat Dec 8 07:26:17 CET 2012


What are the standard ways of counting references in Django? 

I get the feeling that I'm reinventing the wheel below; 
that there's likely some standard way of counting references. 

On Thu, 6 Dec 2012 19:43:23 -0500, jep200404 at columbus.rr.com wrote:

> 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()

That pattern and variations of it appeared several times, 
so I put the code in functions below. The code above would be 
replaced with just c = count_references(previous). 

def count_particular_references(record_or_model, query_keyword_suffix, target):
    c = 0
    for f in record_or_model._meta.get_all_related_objects():
        c += f.model.objects.filter(
            **{f.field.name + query_keyword_suffix: target}).count()
    return c

def count_references(record):
    return count_particular_references(record, '__exact', record)

Imagine one has a File model with information about an actual 
file. Also, one has Book, Magazine, and Flyer models, each of which 
have a ForeignKey pointing to a record in the File model. 
For a given row of File, named file_info, one can find out 
how many other records in the various tables refer to file_info, 
with the following: 

    count_references(file_info)

If one wants to know how many records refer to File records 
that have a particular sha1sum value, one could do: 

    count_particular_references(File, '__sha1sum__exact', sha1sum)



More information about the CentralOH mailing list