Search code examples
pythondjangomodelsdjango-queryset

Method to tackle match counting in django


ive been trying to hack away and figure out how to solve this on my own for a few hours but i can't seem to think of an elegant solution for this. I was wondering if anyone can help.

Heres the model layout (example)

Model A:
candyBarChoices

Model B:
snackLog

Ok so basically the dilemma is this. In the database there are about 15 candy bar choices. Every day when the user logs what they ate, they choose a candy bar. My question is, what is an efficient way to "tally" up each of the candy bar choices given a set of snack logs?

For example: if i provided a QuerySet of 15 snack logs, sometimes the user could have ate multiple candy bars on that day and therefore each snack log could have multiple candy bars. How can i run through this query set and create a compiled data set of the total number of a certain candy bar they ate?

I've come up with multiple really messy solutions using dictionaries, etc. But none of them work without screwing up .. help please.


Solution

  • You should post actual models to help clarify your setup. It looks like you're trying to aggregate over a model instance's related objects. If so, look at the docs on QuerySet aggregation.