Wojciech Ptak
Wojciech Ptak

Reputation: 683

Moving data from one django model to another (django+south) on a living app

I'm trying to move some fields from one django model to a new one. Let's assume I've got a book model:

class Book(models.Model):
  title = models.CharField(max_length=128)
  author = models.CharField(max_length=128)

I decided I need a separate model for author (to add extra data etc.). So, bearing in mind that I have a running application filled with data, the desired layout that keeps compatibility would be:

class Author(models.Model):
  name = models.CharField(max_length=128, null=True) # null at first; filled with datamigration
  nationality = models.CharField(max_length=64, null=True) # we don't have nationality for existing authors, but we'll ask the new ones

class Book(models.Model):
  title = models.CharField(max_length=128)
  author_model = models.ForeignKey(Author, null=True)
  @property
  def author(self):
    return self.author_model.name
  @author.setter
  def author(self, newval):
    self.author_model.name = newval

This way I would have to create schemamigration that adds authors, then a datamigration to transfer the data and fill the author_model_id for books, and finally a datamigration to remove the "author" column from "books" table. The question is, will my migration be valid after changing Book.author from field to property? I mean, if in one of previous migrations South tries to access Book.author (expecting a CharField) it will actually get a property that tries to get nonexistent model. How to do it right?

Upvotes: 3

Views: 1490

Answers (1)

related
related

Reputation: 840

I would just start by renaming the author CharField to author_str in one migration, then add the new model and do the datamigration, and then delete the author_str field.

Django - How to rename a model field using South?

Upvotes: 1

Related Questions