ramusus / django-m2m-history

Django ManyToMany relation field with history of changes
BSD 3-Clause "New" or "Revised" License
4 stars 3 forks source link

How to migrate from Django's ManyToManyField to ManyToManyHistoryField #2

Open ramusus opened 10 years ago

ramusus commented 10 years ago

Now migration from built-in ManyToManyField to ManyToManyHistoryField possible via south http://south.aeracode.org/ only by writing migration by hands:

def forwards(self, orm):

    # Adding field '{{ MODEL }}.{{ FIELD }}.through.time_from'
    db.add_column('{{ M2M_TABLE }}', 'time_from',
        self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True),
        keep_default=False)

    # Adding field '{{ MODEL }}.{{ FIELD }}.through.time_to'
    db.add_column('{{ M2M_TABLE }}', 'time_to',
        self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True),
        keep_default=False)

def backwards(self, orm):

    # Deleting field '{{ MODEL }}.{{ FIELD }}.through.time_from'
    db.delete_column('{{ M2M_TABLE }}', 'time_from')

    # Deleting field '{{ MODEL }}.{{ FIELD }}.through.time_to'
    db.delete_column('{{ M2M_TABLE }}', 'time_to')

Don't forget to substitute {{ M2M_TABLE }}, {{ MODEL }}, {{ FIELD }} variables to real values

ramusus commented 10 years ago

And for Postgres DB I recommend to create partial indexes by putting file {{ MODEL_LOWLETTERS }}.postgresql_psycopg2.sql to sql directory of the application with content

--{{ M2M_TABLE }}

CREATE UNIQUE INDEX {{ M2M_TABLE }}_time_from_3col_uniq
ON {{ M2M_TABLE }} ({{ MODEL_LOWLETTERS }}_id, user_id, time_from)
WHERE time_from IS NOT NULL;

CREATE UNIQUE INDEX {{ M2M_TABLE }}_time_from_2col_uniq
ON {{ M2M_TABLE }} ({{ MODEL_LOWLETTERS }}_id, user_id)
WHERE time_from IS NULL;

CREATE UNIQUE INDEX {{ M2M_TABLE }}_time_to_3col_uniq
ON {{ M2M_TABLE }} ({{ MODEL_LOWLETTERS }}_id, user_id, time_to)
WHERE time_to IS NOT NULL;

CREATE UNIQUE INDEX {{ M2M_TABLE }}_time_to_2col_uniq
ON {{ M2M_TABLE }} ({{ MODEL_LOWLETTERS }}_id, user_id)
WHERE time_to IS NULL;

Don't forget to substitute {{ M2M_TABLE }} and {{ MODEL_LOWLETTERS }} variables to real values