def _bulk_update_runcaseversion_environments_for_lock(self):
        """
        update runcaseversion_environment records with latest state.

        Approach:
          do another raw sql query to get all existing_rcv_envs for this run
          existing_rcv_envs - needed_rcv_envs = list to delete (no longer needed)
          needed_rcv_envs - existing_rcv_envs = list to create
        build a list of RunCaseVersion_environment objects
        and use bulk_create.

        """

        # re-query all the rcvs (including newly created) for this run
        final_rcvs = RunCaseVersion.objects.filter(run=self).select_related(
            "caseversion").prefetch_related("caseversion__environments")

        final_rcv_ids = [x.id for x in final_rcvs]

        # runcaseversion_environments that were there prior to our changes
        prev_rcv_envs_set = set(RunCaseVersion.environments.through.objects.filter(
            runcaseversion_id__in=final_rcv_ids).values_list(
                "runcaseversion_id", "environment_id"))

        # runcaseversion_environment objects we will use to bulk create
        # loop through all cvs and fetch the env intersection with this run
        needed_rcv_envs_tuples = []
        run_env_ids = set(
            self.environments.values_list("id", flat=True))
        for rcv in final_rcvs:
            case_env_ids = set([x.id for x in rcv.caseversion.environments.all()])
            for env in run_env_ids.intersection(case_env_ids):
                needed_rcv_envs_tuples.append((rcv.id, env))
        needed_rcv_envs_set = set(needed_rcv_envs_tuples)

        # get the set of rcv_envs we need to delete because they don't belong
        # to the needed set.
        delete_rcv_envs = prev_rcv_envs_set - needed_rcv_envs_set
        if len(delete_rcv_envs):
            delquery = Q()
            for combo in delete_rcv_envs:
                delquery = delquery | Q(
                    **{"runcaseversion_id": combo[0],
                       "environment_id": combo[1]})
            RunCaseVersion.environments.through.objects.filter(delquery).delete()

        # get the set of rcv_envs we need to create that don't already exist
        needed_rcv_envs_set = needed_rcv_envs_set - prev_rcv_envs_set

        # build all the objects to pass to bulk_create
        needed_rcv_envs = [RunCaseVersion.environments.through(
            runcaseversion_id=needed[0],
            environment_id=needed[1]) for needed in needed_rcv_envs_set]

        RunCaseVersion.environments.through.objects.bulk_create(needed_rcv_envs)
dataset/ETHPy150Open mozilla/moztrap/moztrap/model/execution/models.py/Run._bulk_update_runcaseversion_environments_for_lock/original