Postgresql full-text search query for django ORM

I followed the documentation on FullTextSearch in postgresql. I created the tsvector column and added the information I needed, and finally I created the index. Now, to do a search, I have to execute a query like this

SELECT *, ts_rank_cd(textsearchable_index_col, query) AS rank
FROM client, plainto_tsquery('famille age') query
WHERE textsearchable_index_col @@ query
ORDER BY rank DESC LIMIT 10;

I want to be able to accomplish this with Django ORM so that I can get objects. (A small question here: do I need to add a tsvector column to my model?) I assume that I should use extra () to change the "where" and "table" in the query

Maybe if I changed the request to this, it would be easier:

SELECT * FROM client
WHERE plainto_tsquery('famille age') @@ textsearchable_index_col
ORDER BY ts_rank_cd(textsearchable_index_col, plainto_tsquery(text_search)) DESC LIMIT 10

therefore id 'should do something like:

Client.objects.???.extra(where=[???])

thanks for your help :) Another thing, I use Django 1.1

+3
1

: , :

where_statement = """plainto_tsquery('%s') @@ textsearchable_index_col 
                     ORDER BY ts_rank_cd(textsearchable_index_col, 
                                         plainto_tsquery(%s)) 
                     DESC LIMIT 10"""

qs = Client.objects.extra(where=[where_statement], 
                          params=['famille age', 'famille age'])

Django 1.2, :

Client.objects.raw("""
SELECT *, ts_rank_cd(textsearchable_index_col, query) AS rank
FROM client, plainto_tsquery('famille age') query
WHERE textsearchable_index_col @@ query
ORDER BY rank DESC LIMIT 10;""")
+3

Source: https://habr.com/ru/post/1759472/


All Articles