I have a model that uses PostgreSQL and has field like this:
class MyModel(models.Model):
json_field = models.JSONField(default=list)
This field contains data like this:
[
{"name": "AAAAA", "product": "11111"},
{"name": "BBBBB", "product": "22222"},
]
Now I want to index by json_field -> product field, because it is being used as identification. Then i want to create GinIndex like this:
class Meta:
indexes = [
GinIndex(name='product_json_idx', fields=['json_field->product'], opclasses=['jsonb_path_ops'])
]
When I try to create migration, I get error like this:
'indexes' refers to the nonexistent field 'json_field->product'.
How to create GinIndex that will be used for child attribute in Json Array?
json_field -> 'product'won't return anything as the actual column value is an array. You would needjson_field @> '[{product: "11111"}]'on the SQL level. And for that you need a GIN index on the column, not on an expression.JSONField: relational databases are not good with such data: work with a junction model with aForeignKeyto theProduct. Only if the structure is not fixed or unknown, you should use aJSONField.