def _canonicalize_query(self, query):

        """
        Transform the query dictionary to replace e.g. documents with __ref__ fields.
        """

        def transform_query(q):

            if isinstance(q, dict):
                nq = {}
                for key,value in q.items():
                    nq[key] = transform_query(value)
                return nq
            elif isinstance(q, (list,QuerySet,tuple)):
                return [transform_query(x) for x in q]
            elif isinstance(q,Document):
                collection = self.get_collection_for_obj(q)
                ref = "%s:%s" % (collection,q.pk)
                return ref
            else:
                return q

        return transform_query(query)