{"id":75630,"date":"2020-01-20T11:22:21","date_gmt":"2020-01-20T05:52:21","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75630"},"modified":"2024-04-12T14:17:13","modified_gmt":"2024-04-12T08:47:13","slug":"making-changes-to-a-database-schema","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/","title":{"rendered":"Making Changes to a Database Schema"},"content":{"rendered":"<p>When we introduced the syncdb command earlier, we noted that syncdb merely creates tables that don\u2019t yet exist in your database \u2014 it does <em>not<\/em> sync changes in models or perform deletions of models. If you add or change a model\u2019s field, or if you delete a model, you\u2019ll need to make the change in your database manually. This section explains how to do that.<\/p>\n<p>When dealing with schema changes, it\u2019s important to keep a few things in mind about how Django\u2019s database layer works:<\/p>\n<ul>\n<li>Django will complain loudly if a model contains a field that has not yet been created in the database table. This will cause an error the first time you use the Django database API to query the given table (i.e., it will happen at code execution time, not at compilation time).<\/li>\n<li>Django does <em>not<\/em> care if a database table contains columns that are not defined in the model.<\/li>\n<li>Django does <em>not<\/em> care if a database contains a table that is not represented by a model.<\/li>\n<\/ul>\n<p>Making schema changes is a matter of changing the various pieces \u2014 the Python code and the database itself \u2014 in the right order.<\/p>\n<p><strong>Adding Fields<\/strong> &#8211; When adding a field to a table\/model in a production setting, the trick is to take advantage of the fact that Django doesn\u2019t care if a table contains columns that aren\u2019t defined in the model. The strategy is to add the column in the database, and then update the Django model to include the new field.<\/p>\n<p>However, there\u2019s a bit of a chicken-and-egg problem here, because in order to know how the new database column should be expressed in SQL, you need to look at the output of Django\u2019s manage.py sqlall command, which requires that the field exist in the model. (Note that you\u2019re not <em>required<\/em> to create your column with exactly the same SQL that Django would, but it\u2019s a good idea to do so, just to be sure everything\u2019s in sync.)<\/p>\n<p>The solution to the chicken-and-egg problem is to use a development environment instead of making the changes on a production server. (You <em>are<\/em> using a testing\/development environment, right?) Here are the detailed steps to take.<\/p>\n<p>First, take these steps in the development environment (i.e., not on the production server):<\/p>\n<p>Add the field to your model.<\/p>\n<ul>\n<li>Run pysqlall[yourapp] to see the new CREATETABLE statement for the model. Note the column definition for the new field.<\/li>\n<li>Start your database\u2019s interactive shell (e.g., psql or mysql, or you can use pydbshell). Execute an ALTERTABLE statement that adds your new column.<\/li>\n<li>(Optional.) Launch the Python interactive shell with pyshell and verify that the new field was added properly by importing the model and selecting from the table (e.g., MyModel.objects.all()[:5]).<\/li>\n<\/ul>\n<p>Then on the production server perform these steps:<\/p>\n<ul>\n<li>Start your database\u2019s interactive shell.<\/li>\n<li>Execute the ALTERTABLE statement you used in step 3 of the development environment steps.<\/li>\n<li>Add the field to your model. If you\u2019re using source-code revision control and you checked in your change in development environment step 1, now is the time to update the code (e.g., svnupdate, with Subversion) on the production server.<\/li>\n<li>Restart the Web server for the code changes to take effect.<\/li>\n<\/ul>\n<p>For example, let\u2019s walk through what we\u2019d do if we added a num_pages field to the Book model. First, we\u2019d alter the model in our development environment to look like this:<\/p>\n<pre>class Book(models.Model):\ntitle = models.CharField(maxlength=100)\nauthors = models.ManyToManyField(Author)\npublisher = models.ForeignKey(Publisher)\npublication_date = models.DateField()\nnum_pages = models.IntegerField(blank=True, null=True)\ndef __str__(self):\nreturn self.title\n\n<\/pre>\n<p>(Note: Read the \u201cAdding NOT NULL Columns\u201d sidebar for important details on why we included blank=True and null=True.) Then we\u2019d run the command manage.py sqlall books to see the CREATE TABLE statement. It would look something like this:<\/p>\n<pre>CREATE TABLE \"books_book\" (\n\"id\" serial NOT NULL PRIMARY KEY,\n\"title\" varchar(100) NOT NULL,\n\"publisher_id\" integer NOT NULL REFERENCES \"books_publisher\" (\"id\"),\n\"publication_date\" date NOT NULL,\n\"num_pages\" integer NULL );<\/pre>\n<p>The new column is represented like this:<\/p>\n<pre>   \"num_pages\" integer NULL<\/pre>\n<p>Next, we\u2019d start the database\u2019s interactive shell for our development database by typing psql (for PostgreSQL), and we\u2019d execute the following statements:<\/p>\n<pre>ALTER TABLE books_book ADD COLUMN num_pages integer;<\/pre>\n<p><u>Adding NOT NULL Columns<\/u> &#8211; There\u2019s a subtlety here that deserves mention. When we added the num_pages field to our model, we included the blank=True and null=True options. We did this because a database column will contain NULL values when you first create it.<\/p>\n<p>However, it\u2019s also possible to add columns that cannot contain NULL values. To do this, you have to create the column as NULL, then populate the column\u2019s values using some default(s), and then alter the column to set the NOT NULL modifier. For example:<\/p>\n<pre>BEGIN;\nALTER TABLE books_book ADD COLUMN num_pages integer;\nUPDATE books_book SET num_pages=0;\nALTER TABLE books_book ALTER COLUMN num_pages SET NOT NULL;\nCOMMIT;<\/pre>\n<p>After the ALTER TABLE statement, we\u2019d verify that the change worked properly by starting the Python shell and running this code:<\/p>\n<pre>&gt;&gt;&gt; from mysite.books.models import Book&gt;&gt;&gt; Book.objects.all()[:5]<\/pre>\n<p>If that code didn\u2019t cause errors, we\u2019d switch to our production server and execute the ALTER TABLE statement on the production database. Then, we\u2019d update the model in the production environment and restart the Web server.<\/p>\n<p><u>Removing Fields<\/u> &#8211; Removing a field from a model is a lot easier than adding one. To remove a field, just follow these steps:<\/p>\n<ul>\n<li>Remove the field from your model and restart the Web server.<\/li>\n<li>Remove the column from your database, using a command like this:<\/li>\n<\/ul>\n<pre>ALTER TABLE books_book DROP COLUMN num_pages;<\/pre>\n<p><u>Removing Many-to-Many Fields<\/u> &#8211; Because many-to-many fields are different than normal fields, the removal process is different:<\/p>\n<ul>\n<li>Remove the ManyToManyField from your model and restart the Web server.<\/li>\n<li>Remove the many-to-many table from your database, using a command like this:<\/li>\n<\/ul>\n<pre>DROP TABLE books_books_publishers;<\/pre>\n<p><u>Removing Models<\/u> &#8211; Removing a model entirely is as easy as removing a field. To remove a model, just follow these steps:<\/p>\n<ul>\n<li>Remove the model from your py file and restart the Web server.<\/li>\n<li>Remove the table from your database, using a command like this:<\/li>\n<\/ul>\n<pre>DROP TABLE books_book;6: The Django Administration Site\n\n<\/pre>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When we introduced the syncdb command earlier, we noted that syncdb merely creates tables that don\u2019t yet exist in your database \u2014 it does not sync changes in models or perform deletions of models. If you add or change a model\u2019s field, or if you delete a model, you\u2019ll need to make the change in&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[8756],"class_list":["post-75630","page","type-page","status-publish","hentry","category-django-web-development","tag-making-changes-to-a-database-schema"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Making Changes to a Database Schema - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Making Changes to a Database Schema - Tutorial\" \/>\n<meta property=\"og:description\" content=\"When we introduced the syncdb command earlier, we noted that syncdb merely creates tables that don\u2019t yet exist in your database \u2014 it does not sync changes in models or perform deletions of models. If you add or change a model\u2019s field, or if you delete a model, you\u2019ll need to make the change in...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:13+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/\",\"name\":\"Making Changes to a Database Schema - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T05:52:21+00:00\",\"dateModified\":\"2024-04-12T08:47:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Making Changes to a Database Schema\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Making Changes to a Database Schema - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/","og_locale":"en_US","og_type":"article","og_title":"Making Changes to a Database Schema - Tutorial","og_description":"When we introduced the syncdb command earlier, we noted that syncdb merely creates tables that don\u2019t yet exist in your database \u2014 it does not sync changes in models or perform deletions of models. If you add or change a model\u2019s field, or if you delete a model, you\u2019ll need to make the change in...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:13+00:00","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/","name":"Making Changes to a Database Schema - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T05:52:21+00:00","dateModified":"2024-04-12T08:47:13+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/making-changes-to-a-database-schema\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Making Changes to a Database Schema"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75630","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75630"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75630\/revisions"}],"predecessor-version":[{"id":83339,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75630\/revisions\/83339"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75630"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75630"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75630"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}