In this article you will know about how you can change you models as per requirement of your application.
Your models are not the final thing. Your models will change as your Django project gains more features. You might add or remove fields or change their types and options..
When you change the definition of a model, the database tables used to store these models have to be changed too. If your model definitions don’t match your current database schema, you will most likely run into a django.db.utils.OperationalError.
So the question is how you can makes changes in the database tables? By creating and applying a migration.
Let’s change the model to look like this:
class ProductPrice(models.Model): date = models.DateTimeField(auto_now_add=True) price = models.DecimalField(max_digits=7, decimal_places=2) volume = models.PositiveIntegerField()
class ProductPrice(models.Model): date = models.DateTimeField(auto_now_add=True) price = models.DecimalField(max_digits=7, decimal_places=2) volume = models.DecimalField(max_digits=7, decimal_places=3)
If you don’t run database migrations, you would have to figure out the SQL syntax to turn a PositiveIntegerField into a DecimalField. Luckily, Django will handle that for you. Just tell it to make migrations by just running this command in terminal:
$ python manage.py makemigrations
Now you apply this migration to your database by running command in your terminal:
$ python manage.py migrate
In order to check if your migrations successfully applied. Use dbshell to verify that the changes had an effect.
$ python manage.py dbshell SQLite version 3.19.3 2019-03-01 02:09:14 Enter ".help" for usage hints. sqlite> .schema --indent gbs_blog_productrice CREATE TABLE IF NOT EXISTS "gbs_blog_productrice" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "date" datetime NOT NULL, "price" decimal NOT NULL, "volume" decimal NOT NULL );