Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2217

Convert Raw SQL to Django ORM code , possibility

Is it possible to perform something like this with only Django ORM?

        with connection.cursor() as cursor:
            cursor.execute(
                """SELECT word FROM ts_stat(
                'SELECT to_tsvector(''simple'', description) FROM api_product');""",
                #[source, ]
            )
            words_in_product_model = frozenset(
                more_itertools.one(word) for word in cursor.fetchall()

db-Postgres 11 Thanks

Upvotes: 1

Views: 302

Answers (1)

Wolph
Wolph

Reputation: 80111

The SearchVector class does use the to_tsvector but I don't think the ts_stat is available.

When initially looking at your question I completely missed the fact that ts_stat takes a string instead of just a regular result. That changes the implementation significantly and I'm not sure what's the best way of implementing this... but I'll give you a simple hack to work around it using the raw method on a queryset.

from django.db import models


class TsStat(models.Model):
    word = models.CharField(max_length=256)
    ndoc = models.PositiveIntegerField()
    nentry = models.PositiveIntegerField()

    class Meta:
        managed: False



vector_query = models.ApiProduct.objects.annotate(
    search=Func(Value('simple'), 'description', function='to_tsvector'),
).values('search')

results = TsStat.objects.raw('SELECT * FROM ts_stat(%s)' % vector_query.query)

But this is obviously untested, the syntax might be slightly different and you'll might have to include the SearchVector immediately instead of through filter.

Upvotes: 2

Related Questions