Sum over the values of the specified field. :param field: the field to sum over; use dot notation to refer to embedded document fields
(self, field)
| 1562 | return queryset |
| 1563 | |
| 1564 | def sum(self, field): |
| 1565 | """Sum over the values of the specified field. |
| 1566 | |
| 1567 | :param field: the field to sum over; use dot notation to refer to |
| 1568 | embedded document fields |
| 1569 | """ |
| 1570 | db_field = self._fields_to_dbfields([field]).pop() |
| 1571 | pipeline = [ |
| 1572 | {"$match": self._query}, |
| 1573 | {"$group": {"_id": "sum", "total": {"$sum": "$" + db_field}}}, |
| 1574 | ] |
| 1575 | |
| 1576 | # if we're performing a sum over a list field, we sum up all the |
| 1577 | # elements in the list, hence we need to $unwind the arrays first |
| 1578 | ListField = _import_class("ListField") |
| 1579 | field_parts = field.split(".") |
| 1580 | field_instances = self._document._lookup_field(field_parts) |
| 1581 | if isinstance(field_instances[-1], ListField): |
| 1582 | pipeline.insert(1, {"$unwind": "$" + field}) |
| 1583 | |
| 1584 | result = tuple(self._document._get_collection().aggregate(pipeline)) |
| 1585 | |
| 1586 | if result: |
| 1587 | return result[0]["total"] |
| 1588 | return 0 |
| 1589 | |
| 1590 | def average(self, field): |
| 1591 | """Average over the values of the specified field. |