I'd like to refactor a number of django apps in a way which involves moving Models from one app into another where they can be more readily reused.
A number of these models have either ForeignKey relationships or M2M relationships to other models (such as User). For example:
class Department(models.Model):
name = models.CharField(max_length=255)
reviewers = models.ManyToManyField(User)
In most cases, the models do not change, so I've currently just redefined them in the new app. This of course causes problems with related_name, since I have the same model defined in two separate apps, and manage.py syncdb
gives the following error:
new_app.department: Accessor for m2m field 'reviewers' clashes with related m2m field 'User.department_set'. Add a related_name argument to the definition for 'reviewers'.
old_app.department: Accessor for m2m field 'reviewers' clashes with related m2m field 'User.department_set'. Add a related_name argument to the definition for 'reviewers'.
When doing this, I also need to migrate the data keeping any automatically generated database ids. I'd planned on using the ORM to do the migration, thinking something like the following would work:
from newapp.models import Department
import oldapp.models as old
for obj in old.Department.objects.all():
new_obj = Department(id=obj.id, name=obj.name)
new_obj.save()
for r in obj.reviewers.all():
new_obj.reviewers.add(r)
new_obj.save()
Of course, the related_name
problem prevents me from doing this.
How have others made this sort of code refactor and migration possible? Thanks!