Would like a callback on models.Field during SQL generation
|Reported by:||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
It would be useful if Fields had the opportunity to specify SQL code to be included when generating the SQL for their model.
I am currently trying to add some stuff to the SQL generated by Django to implement full text indexes in PostgreSQL for several models. Each model requires the following to be added:
-- full text indexing on blogs_post CREATE INDEX blogs_post_fts ON blogs_post USING gin (vector); CREATE FUNCTION blogs_post_fts_update () RETURNS trigger AS $$ BEGIN NEW.vector = ts2.to_tsvector ('default', NEW.title || ' ' || NEW.body); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER blogs_post_fts_update BEFORE INSERT OR UPDATE ON blogs_post FOR EACH ROW EXECUTE PROCEDURE blogs_post_fts_update (); -- end of full text indexing on blogs_post
Entering this for every table that I want to create an index upon is really annoying!
It is possible to generate these SQL statements based on information in the model definition:
class Blog (models.Model): title = models.TextField () body = models.TextField () vector = TsvectorField (fields = ['title', 'body'])
In order to do this, I created a custom field type that adds the actual field to the CREATE TABLE statement:
class TsvectorField (models.Field): def __init__ (self, fields, *args, **kwargs): if kwargs.pop ('editable', False) == True: raise ValueError ('TsvectorFields can not be editable') super (TsvectorField, self).__init__ (*args, **kwargs) # do something with fields! def db_type (self): return 'ts2.tsvector'
But at this point I am stuck: as far as I can see, there is nowhere to place the code to generate the above SQL.
I propose that
django.core.management.sql.sql_indexes_for_model by modified to call a method on each field, named something like
get_sql_index. This method would generate & return the above SQL statements.
Change History (5)
comment:1 Changed 10 years ago by
|Summary:||Would like a callback on field creation → Would like a callback on models.Field during SQL generation|