+We begin by specifying a customer by using his `id` column from the `Contribution` model as `Contribution.customer_id`. This is possible because both models are related as specified by the `relationship` method found in the `Customer` model. Using `func`, we invoke the `sum` method on the `contribution` column of the `Contribution` model. Intentionally, this adds all data in the `contribution` column. But before we can finish, we want to ensure that the addition applies only to the said customer whose name keeps appearing multiple times. Therefore, we combine his contribution by using `group_by(Contribution.customer_id)`. What we have so far is the total contribution of a single customer. The `.all()` method is applied to return all customers in the database. In the end, we will have a list with customers' data such as `[('Gitau', 100), ('Njeri', 2200), ('Muthoni', 400)]` assuming that Gitau has an `id=1`, Njeri has `id=2` and Muthoni has `id=3`. This list is passed to the templates as a variable called `contributions`.
0 commit comments