Я создал функцию, которая позволяет подсчитать число status
и присвоить его переменной.
def get_types_count_display(self):
dispatches = self.route_dispatches.values_list('dispatch_id', flat=True)
dispatches = Dispatch.objects.filter(id__in=dispatches)
d = { "dispatches_types": list(dispatches.values('status_id')) }
pendents = len([1 for e in d["dispatches_types"] if e["status_id"]==1])
delivered = len([1 for e in d["dispatches_types"] if e["status_id"]==2])
partial = len([1 for e in d["dispatches_types"] if e["status_id"]==3])
undelivered = len([1 for e in d["dispatches_types"] if e["status_id"]==4])
return dict(pendents=pendents, delivered=delivered, partial=partial, undelivered=undelivered)
, где d
- моя переменная, в которой хранится содержащийся в ней словарь
{'dispatches_types': [{'status_id': 2}, {'status_id': 1}, {'status_id': 1}, {'status_id': 1}, {'status_id': 2}]}
или
{'dispatches_types': []}
это динамически
проблема, с которой я столкнулся, заключается в том, что когда вы снова набираете for
, снова вызываетенабор запросов, запрос становится тяжелее.
Как я могу оптимизировать эту функцию?