Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index just selected json key using Django functionality instead of all keys?

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.

like image 831
TitanFighter Avatar asked Oct 29 '25 10:10

TitanFighter


1 Answers

Functional indexes is going to be available in Django 3.2 in April. This finally should allow to build needed indexes from Django.

like image 179
TitanFighter Avatar answered Nov 01 '25 00:11

TitanFighter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!