Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the Django data type in models without dropping the table

I have created a Django application. Now i wanted to change the field type for 1 of my db field in models. Since there are some records already in the database with the present type, i guess its not possible to change the type by simply changing it in models.py. By googling i came to know that it can be changed without dropping the tables by changing it through sql console. But being a Django newbie i am not able to do this. Can somebody help me to do this? This is my models.py

class EmployeeDetails(models.Model):
    userName = models.CharField(max_length=200)
    designation = models.CharField(max_length=200)
    employeeID = models.IntegerField()
    contactNumber = models.CharField(max_length=200)
    project = models.CharField(max_length=200)
    dateOfJoin=models.TextField()

Now i want to change the dateOfJoin = models.DateField(). How can i change the TextFieild to DateField without droping the table by using sql console commands?

like image 288
rv_k Avatar asked Nov 30 '22 17:11

rv_k


2 Answers

The app you need is South
Here are the steps (refer to the doc for more details) :

./manage.py convert_to_south yourapp 

this will create a migration folder and fake a first migration

Then add a new_dateOfJoin DateField in your models.py :

./manage.py migrate yourapp 

this will create and apply immediatly a migration (named 0002_...) to add this field in the db

Create a datamigration 0003 file where you will just cast your text value to date and save it in your new field Then apply this migration :

./manage.py migrate yourapp

Modify your models.py file to comment out the old datefield and migrate again (this will create the 0004_.... migration file)

The last step is to rename the db field so you don't have to modify your existing code:

./manage.py schemamigration yourapp rename_dateofjoin --empty

This will create an empty schema migration file named 0005_rename_dateofjoin
Manually modify this 0005 file like explained here , but use db.rename_column('app_foo', 'name', 'full_name') like in this other example.

Dropping your whole table instead of these 5 steps can be easier, but if you have multiple instance of the app (like a working production server and a develpement machine) you need this kind of tools.
With better understanding of South, one could also do this in less than 5 steps, but as migrations can be tricky to undone or reproduce sometimes, I prefer to have distinct steps...

like image 64
3 revs Avatar answered Dec 04 '22 06:12

3 revs


The South project is commonly used to migrate schemas and data. I'm not sure offhand if it can be used to convert a text field into a date field, but I wouldn't be surprised if it could.

like image 41
Blair Avatar answered Dec 04 '22 06:12

Blair