Serialize Haystack SearchQuerySet
<p>I have some Django queries dumped in files that are delayed so I pass as parameter <code>sql_with_params</code> to later execute in the delayed a <code>raw</code> query.</p>

<p>I have migrated all queries to haystack so I wan't to do the same with <code>SearchQuerySet</code>.</p>

<p>Is there any way to get the raw_query of an already constructed SearchQuerySet?</p>

<p>PD: I am using ElasticSearch</p>

<p>Sure, here's one way that unfortunately requires a bit of plumbing. You can create a custom search engine and set its query to your own query definition inheriting from <code>ElasticsearchSearchQuery</code>:</p>

<pre><code>from haystack.backends.elasticsearch_backend import ElasticsearchSearchEngine, ElasticsearchSearchQuery


class ExtendedElasticsearchSearchQuery(ElasticsearchSearchQuery):
    def build_query(self):
        raw_query = super(ExtendedElasticsearchSearchQuery, self).build_query()
        # TODO: Do something with raw query
        return raw_query

class ExtendedElasticsearchSearchEngine(ElasticsearchSearchEngine):
    query = ExtendedElasticsearchSearchQuery
</code></pre>

<p>and reference that from your settings:</p>

<pre><code>HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'myapp.mymodule.ExtendedElasticsearchSearchEngine',
        'URL': 'http://localhost:9200/',
        'INDEX_NAME': 'haystack'
    },
}
</code></pre>

python django elasticsearch django-haystack