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

Source: Internet
Author: User
Tags psql
This article mainly introduces the example of adding fields to the Django model through databases. Django is the most popular Pythonweb development framework. if you need a friend, refer to the following: borrow a book first) the data model:

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 %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 configuration table (or model), you can use the feature that Django does not care about whether the table contains columns not in the model. The policy is to add fields to the database, and then synchronize the Django model to include new fields.

However, there is a problem of chicken, eggs, and eggs. to understand the SQL statements for adding columns, you need to use Django manage. run the py sqlall command to check whether the field already exists in the model. (Note: You do not have to use the same SQL statement as Django to create a new field, but it is indeed a good idea that it can keep everything synchronized .)

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

First, enter the development environment (that is, not in the release environment ):

Add fields to your model.

Run manage. py sqlall [yourapp] to test the new create table statement of the model. Note the column definition for the new field.

Enable the interactive command interface of your database (for example, psql or mysql, or you can use manage. py dbshell ). Execute the alter table statement to add a new column.

Use the manage of Python. py shell, by importing the model and the selected form (for example, MyModel. objects. all () [: 5]) to verify whether the new field is correctly added. if everything goes well, no error is reported for all statements.

Perform these steps again on your product server.

Start the interaction interface of the database.

Execute the alter table statement in step 3 in the development environment.

Add new fields to the model. If you have used a version control tool and submitted your modifications in the development environment in step 1, you can update your code in the production environment (for example, if you use Subversion, execute svn update.

Restart the Web server to make the modification take effect.

For example, add a num_pages field to the Book model in Chapter 5. 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


Then, run manage. py sqlall books to view the create table statement. The specific content of the statement depends on the database you are using, which is probably like this:

CREATE TABLE "books_book" (  "id" serial NOT NULL PRIMARY KEY,  "title" varchar(100) NOT NULL,  "publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id"),  "publication_date" date NOT NULL,  "num_pages" integer NULL);

The newly added field is represented as follows:

"num_pages" integer NULL

Next, we will run the database client in the development environment. for PostgreSQL, run psql. then, I will 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 add the num_pages field, we use the options blank = True and null = True. This is because this database field contains null values when we create it for the first time.

However, you can add fields that do not contain null values. To achieve this effect, you must first create a NULL field, then fill the value of this field with a default value, and then change this 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 not to add the blank = True and null = True options to the model.

After the alter table statement is executed, verify that the modification 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, execute the command alter table in the database of the production environment, update the model in the production environment, and restart the web server.

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.