I have the next model:
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField, SearchVector
from django.db import models
class ProfileUser(models.Model):
    name = JSONField()
    search_vector = SearchVectorField(null=True)
    class Meta:
        indexes = [GinIndex(fields=["search_vector"], name="user_full_name_gin_idx")]
    def save(self, *args, **kwargs):
        super(ProfileUser, self).save(*args, **kwargs)
        ProfileUser.objects.filter(pk=self.pk).update(search_vector=SearchVector('name'))
        # I have tried this, but this does not work.
        # ProfileUser.objects.filter(pk=self.pk).update(search_vector=SearchVector(KeyTextTransform('name', 'name')))
And name looks like [{'name': 'Random Name', 'lang': 'en'}, {'name': 'Какое-то Имя', 'lang': 'ru'}].
Currently the code above indexes both name and lang keys. Is it possible using Django to index just name key? I found how to workaround this using SQL directly, but I just want to know, if it is possible to do that just via Django.
I use Django 2.2 and PostgreSQL 12.
Functional indexes is going to be available in Django 3.2 in April. This finally should allow to build needed indexes from Django.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With