As part of
django-modeltrans, I'm trying to add a GinIndex to the model when a custom Field is added. The simplified version of my naive implementation looks like this:
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
class CustomJSONField(JSONField):
def contribute_to_class(self, cls, name):
super(CustomJSONField, self).contribute_to_class(cls, name)
index = GinIndex(fields=[name])
index.set_name_with_model(cls)
cls._meta.indexes.append(index)
This works fine when an initial migration is created for the model, but becomes a bit undefined when the custom field is added to an existing model:
1. When I add the custom field, with class Meta: indexes = [] present (can also be non-empty), the index is added twice (with the same name).
2. When I add the custom field with the index, the index is correctly added
3. When I remove the index from the custom field, the index is correctly removed.
4. When I re-add the index to the custom field, the change is not detected.
As there's no documented support for adding indexes in Field.contribute_to_class()
, can you explain why Django is at fault and/or propose a patch?
Which I understand. I'm open to suggestions for other solutions to add an Index to the model along with the custom field.
But using contribute_to_class seems the cleanest way to do it, and support seems to be almost/halfway there. Is it reasonable to expect this to work? If so, I'm willing to create a patch, but any help/pointers from someone with more in depth knowledge of migrations is appreciated.
Jan Pieter.