Example of adding a field to a Django model from a database

Source: Internet
Author: User
Tags psql svn update
First borrow this data model of book:

From django.db import Modelsclass Publisher (models. Model):  name = models. Charfield (max_length=30)  address = models. Charfield (max_length=50) City  = models. Charfield (max_length=60)  state_province = models. Charfield (max_length=30)  country = models. Charfield (max_length=50)  website = models. Urlfield ()  def __unicode__ (self):    return Self.nameclass Author (models. Model):  first_name = models. Charfield (max_length=30)  last_name = models. Charfield (max_length=40)  email = models. Emailfield ()  def __unicode__ (self):    return u '%s '% (Self.first_name, Self.last_name) class book (Models. Model):  title = models. Charfield (max_length=100)  authors = models. Manytomanyfield (Author)  publisher = models. ForeignKey (Publisher)  publication_date = models. Datefield ()  def __unicode__ (self):    return Self.title


Add Field
When you want to add a field to a Product Setup table (or model), the trick to use is to take advantage of Django's lack of concern about whether the table contains columns that are not in the model. The strategy is to add fields to the database now, and then synchronize the Django model to include the new fields.

However, there is a chicken egg problem, because you want to know the new column of SQL statements, you need to use the Django manage.py sqlall command to view, and this requires that the field has already existed in the model. (Note: You don't have to create a new field with the same SQL statement as Django, but it's a good idea to keep everything in sync.) )

The solution to this chicken-egg problem is to implement this change in a developer environment rather than in a publishing environment. (You're using a test/development environment, right?) Here are the specific implementation steps.

First, enter the development environment (i.e., not in the publishing environment):

Add a field to your model.

Run manage.py Sqlall [YourApp] to test the model new CREATE TABLE statement. Note the column definition for the new field.

Open the interactive command interface for your database (for example, Psql or MySQL, or you can use manage.py Dbshell). Execute the ALTER TABLE statement to add a new column.

Using the Python manage.py shell, verify that the new field is added correctly by importing the model and selecting the form (for example, MyModel.objects.all () [: 5]), and that all statements will not be error-proof if all goes well.

Then implement these steps again on your product server.

Start the interactive interface of the database.

Perform the ALTER TABLE statement in the third step of the development environment step.

Adds a new field to the model. If you're using a version control tool, and in the first step, you've already submitted your changes in the development environment, you can now update your code in a production environment (for example, if you're using subversion, perform SVN update.)

Restart the Web server for the changes to take effect.

Let's practice, for example, adding a num_pages field to the book model in the fifth chapter. First, we will change the model in the development environment to the following form:

Class book (Models. Model):  title = models. Charfield (max_length=100)  authors = models. Manytomanyfield (Author)  publisher = models. ForeignKey (Publisher)  publication_date = models. Datefield ()  **num_pages = models. Integerfield (Blank=true, null=true) * *  def __unicode__ (self):    return Self.title


We then run the command manage.py Sqlall books to view the CREATE TABLE statement. The exact content of the statement depends on the database you are using, presumably like this:

CREATE TABLE "Books_book" (  "id" serial NOT NULL PRIMARY KEY,  "title" varchar (+) NOT NULL,  "publisher_id" in Teger NOT NULL REFERENCES "Books_publisher" ("id"),  "publication_date" date is not null,  "Num_pages" integer NULL );

The newly added fields are represented as follows:

"Num_pages" Integer NULL

Next, we will run the database client on the development environment, if it is PostgreSQL, run Psql, and then I execute the following statement.

ALTER TABLE books_book ADD COLUMN num_pages integer;

Add a non-null field

Here is a subtle point worth mentioning. When we added the field num_pages, we used the blank=true and null=true options. This is because this database field contains null values when we first created it.

However, it is also possible to add fields that cannot contain null values. To achieve this effect, you must first create a NULL type field, then populate the field's value as a default value, and then change the field to not null. For example:

BEGIN; ALTER TABLE books_book ADD COLUMN num_pages integer; UPDATE Books_book SET num_pages=0; Alter TABLE Books_book ALTER COLUMN num_pages SET not NULL; COMMIT;

If you do this, remember that you do not add the Blank=true and null=true options to the model.

After the ALTER TABLE is executed, we want to verify that the result is correct. Start Python and execute the following code:

>>> from mysite.books.models import book>>> Book.objects.all () [: 5]

If no exception occurs, we will switch to the production server and then execute the command in the database of the production environment alter TABLE and then we update the model in the production environment and finally restart the Web server.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.