Django model refactoring and migration

I would like to refactor several django applications so that they move models from one application to another where they can be reused more easily.

Some of these models have ForeignKey relationships or M2M relationships with other models (such as User). For example:

class Department(models.Model):
    name = models.CharField(max_length=255)
    reviewers = models.ManyToManyField(User)

      

Most of the time the models don't change, so currently I just override them in a new application. This of course causes problems with related_name as I have the same model defined in two separate applications 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'.

      

That being said, I also need to migrate data preserving any auto-generated database IDs. I was planning on using an ORM for migration, thinking something like the following:

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 problem related_name

prevents me from doing this.

How can others do this kind of refactoring and code migration? Thank!

+2


source to share


2 answers


Have you used a migration tool like South or django-evolution ?



+6


source


You can solve the closest problem very easily by simply providing a related_name argument to the ForeignKey in the new or old model, just like the error message reported. Not sure if it will solve all your problems with this migration, but it will take you one step further.



0


source







All Articles