Just like the data migration example for the docs, I’ve recently realized my models setup made little sense. However, I’m having issues trying to change it.
I have a User
model, a One-on-one Profile
model and a Team
model. Right now, Team has a FK to Profile (the field leader
). I’m trying to switch it to the User
model and save myself from adding select_related("leader__user")
every single time
My current approach
- Rename old FK
leader_profile
- Create new FK
leader
- Use a data migration to backfill information
- Delete
leader_profile
So, in detail:
- Rename old FK
operations = [
migrations.RenameField(
model_name='team',
old_name='leader',
new_name='leader_profile',
),
]
- Create new FK:
# models.py
leader_profile = models.ForeignKey(Profile)
leader = models.ForeignKey(User)
- Data migration
# migration file
from django.db import migrations
def backfill_leader(apps, schema_editor):
# We can't import the Team model directly as it may be a newer
# version than this migration expects. We use the historical version.
Team = apps.get_model("dashboard", "Team")
for team in Team.objects.all():
team.leader = team.leader_profile.user
team.save()
class Migration(migrations.Migration):
operations = [
migrations.RunPython(backfill_leader, reverse_code=migrations.RunPython.noop),
]
- Delete
leader_profile
My current issue:
I’m running into a snag when trying this. The error I get is django.db.utils.ProgrammingError: relation "app_team_leader_id_bd9f9f21" already exists
which is weird. I would think that renaming the field would also rename the automatic indexes. I saw there was a ticket for something related, but I’m not sure that’s what affecting me.
How do I solve this?