I have a UserProfile
model that refers to my User
model with a OneToOneField
. I also use the post_save
signal to auto create the UserProfile
when the user is created. This works great apart from when creating a user through the admin (where I use an inline) when I get an error about duplicate profile. This answer recommends setting the primary key to be the OneToOneField referring to user.
So before:
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
# ...
subjects = models.ManyToManyField(Subject, null=True, blank=True)
After
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
# ...
subjects = models.ManyToManyField(Subject, null=True, blank=True)
I'm trying to do that using the migrations in Django 1.7, but life is complicated by the fact that the profile has a number of ManyToManyField
- so they all refer to the id
field of the UserProfile
model. Using makemigrations
creates the migrations for making the user the primary key, and dropping the old id field, but it ignores the ManyToManyField.
I'm currently going down a rabbit hole of using lots of RunSQL
statements in the migration to modify the through table for the ManyToManyField
. I've just hit another error where the name of the constraint is not the same in one table as another.
So my question is: is there a method in Django migrations that will do the work of changing the through table so it refers to the new primary key, updating all the constraints, keys etc? If not, what's the best way to handle this situation?
I'm using Django 1.7 with MySQL.