Lost on where to put Annotate/Aggregate

I’m working with Django for the first time and have gotten myself stuck. I have Model1 that has a ‘1 to many’ relationship with Model2. I want to be able to sum up all the ‘cost’ fields in Model2 that are related to Model1. It seems like that should be done using an annotate function similar to this:

Book.objects.values('author').annotate(num_books=Count('book_name'))

Where I have gotten myself stuck is I don’t know where to put this code… is it within the Model1 model.py class? Some other view.py class

My Object Orientated idea says that it should be within the Model1 model.py code, but I can’t seem to get that to make sense. If it wasn’t using Django, I would just have a function that iterates thru all the child records and sums that up and returns the value and just do Model1.getsum() where needed. Do I just replace this ‘annotate’ function where I would make such a getsum() call?

Thanks in advance. I’m sure this should be simple, but its got me stuck :smiley:

I am fairly new but I think I got this.
You put this code in your view and pass it to the template in the context dictionary.

Does that make sense?

To add a little bit to @qvisty’s response - That line, by itself, doesn’t actually “do” anything other than define a database query that can be run at a later time.

Side note: Have you (or are you) worked your way through either the Official Django Tutorial or the Django Girls Tutorial? I generally recommend them as being the best place to start since either one of them are going to teach you the fundamentals you’ll need to learn to be successful with Django.

Traditionally, you would use that statement in an assignment statement, and then process the individual instances of Book as necessary.

e.g. in your view, you may have:
book_list = Book.objects...
you would then iterate over book_list to do “something” with it, such as creating an html table to be rendered in the browser.

(Side note: I say “traditionally” above because that’s not the only way it which that query can be used. For example, you could also use it in a custom manager - but if you’re not familiar with managers, you don’t need to worry about those other cases yet.)

1 Like

I’ve been using the Django for Beginners book plus any other resources I can find including Django girls and the official tutorials. I would not have gotten this far without them.

I’m a bit familiar with what you mention about creating the book_list in the view using the .all or .filter options. How would that work with the annotate(num_books=Count('book_name'))… is it any different?

I think it makes some sense, but not complete. I haven’t been able to find a good example online that has “complete” code. It usually has sample models and then a 1 line about using annotate(num_books=Count('book_name')), but never shows the filename or complete file they put it in.

No, it’s not any different.

You probably want to spend some time with the docs at