diff --git a/beat/web/backend/models/environment.py b/beat/web/backend/models/environment.py index e42694647a215f392b7c42202900382646f0c07a..3dc14b3334dbc797d0945af893e1bf2a15c6a9f9 100755 --- a/beat/web/backend/models/environment.py +++ b/beat/web/backend/models/environment.py @@ -27,6 +27,7 @@ from django.db import models from django.core.urlresolvers import reverse +from django.db.models import Count, Q from ...code.models import Code from ...common.models import Shareable @@ -45,6 +46,41 @@ class EnvironmentManager(ShareableManager): name, version = fullname.rsplit(" ", 1) return self.get_by_natural_key(name, version[1:-1]) + def use_count(self, block_list): + """Returns a list of environments used for the blocks in that list with + how many times each has been used. + + Parameters: + block_list (Block) : list of blocks to analyze. + + Returns: + list: annotated environments with the number of time they have been + used for blocks that are done. + """ + + from ...experiments.models import Experiment + from ...experiments.models import Block + + # Tries to figure through a maximum if blocks in the list have been + # successfully used inside an environment. + + # Case 1) The block is part of an experiment that was successful + # Case 2) The block is part of an experiment that is not successful + # (failed or other), but it is CACHED (if not cached, then we can't + # attest anything about the block/environment relationship!) + + return ( + self.filter( + blocks__in=block_list.filter( + Q(experiment__status=Experiment.DONE) + | ((~Q(experiment__status=Experiment.DONE)) & Q(status=Block.DONE)) + ) + ) + .annotate(use_count=Count("id")) + .order_by("-creation_date") + .distinct() + ) + # ----------------------------------------------------------