Search code examples
mongodbdjango-modelsdjango-nonrel

Adding new ForeignKey field to an existing django MongoDB model?


I am using "Django Non-rel" and Django-MongoDB ORM" for my project with MongoDB Nosql database. I need to change one of my model and add a ForeignKey field to it.I thought that South would help in data migration but i got to know that South doesnot support MongoDB.My model is like this:

class Projects(models.Model):
    projectName =models.CharField(max_length = 100,unique=True,db_index=True)
    projectManager = models.ForeignKey('auth.User')

I need to add states = models.ForeignKey('States') to my model.But i have no idea how to do this without south so that it doesnot create problem in my existing database.Please help guys :(


Solution

  • I'm using django non-rel on appengine, this might not translate perfectly to MongoDB, but I suspect it's the same.

    I've been doing the following, it takes a few steps.

    1. Updated your model with null=True: projectManager = models.ForeignKey('auth.User', null=True)

    This ensures that your existing models in the database are not going to cause Django to throw exceptions.

    1. Write a script that will query all Projects and update their projectManager fields

    2. Update the model again with null=False projectManager = models.ForeignKey('auth.User')

    Now that none of the objects in the DB have a null field for projectManager, it's ok to remove the null flag.