Home > Software design >  Using Django-modeltranslation in combination with PostgreSQL SearchVector
Using Django-modeltranslation in combination with PostgreSQL SearchVector

Time:01-20

I'm using django-modeltranslation to translate model fields. And suppose I have the following model (where the name is translated in the DB):

class Book(models.Model):
    name = models.CharField(max_length=90)

Then, in a DRF view, I have an endpoint that takes a query text and searches through the book names using this code:

from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank

class BookView(APIView):

    def get(self, request):
        q = request.get('q')
        vector = SearchVector('name') # this is where the issue is
        query = SearchQuery(q)
        matches = Book.objects.annotate(rank=SearchRank(vector, query))\
                      .filter(rank__gt=0.1)\
                      .order_by('-rank')
        # etc.

This works great when I was working with English only. But now I added a new language, and all aspects of the localisation are working fine, except this search. It's looking at the name_en field values only.

If the target language is German for example, and I explicitly change the following line from:

vector = SearchVector('name')

to:

vector = SearchVector('name_de')

Then the search works over the correct field. Is there a way to pass in the correct field to SearchVector?

CodePudding user response:

IIUC, you can just use get_language():

from django.utils.translation import get_language
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank

class BookView(APIView):

    def get(self, request):
        q = request.get('q')
        vector = SearchVector(f'name_{get_language()}')
        query = SearchQuery(q)
        matches = Book.objects.annotate(rank=SearchRank(vector, query))\
                      .filter(rank__gt=0.1)\
                      .order_by('-rank')
  •  Tags:  
  • Related