Well, books can be redefined as: def books(self): progs = self.programs.all() return sum([prog.publications.all().filter(type=u'Book').count() for prog in progs])
and likewise for the other methods. On Mar 27, 1:27 pm, Rodrigo Culagovski <[EMAIL PROTECTED]> wrote: > My application has the following models: Researcher, Program and > Publication. > Each Researcher has 0 or more Programs as a ManyToManyField, and each > Program has 0 or more Publications also as a ManyToManyField. > Publication has a 'type' attribute which is a CharField, and has > choices: Book, Article or Other. > > I need to retrieve the number of Publications of each type for each > Program of a given Researcher. > > Within the Researcher class I define: > > def books(self): > count = 0 > for progs in self.programs.all(): > for pub in progs.publications.all(): > if pub.type== u"Book": > count += 1 > return count > > def articles(self): > count = 0 > for progs in self.programs.all(): > for pub in progs.publications.all(): > if pub.type== u"Article": > count += 1 > return count > > def others(self): > count = 0 > for progs in self.programs.all(): > for pub in progs.publications.all(): > if pub.type== u"Other": > count += 1 > return count > > This lets me get {{ researcher_instance.books }} etc. in my templates. > However, this seems excessively verbose and repeating oneself, and it > seems like this problem would already have come up many times. Is > there a more idiomatic, pythonic and djangoic way to do this? > > Thanks, > > Rodrigo --~--~---------~--~----~------------~-------~--~----~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---