Full introduction to running Python applications in the Django framework

Source: Internet
Author: User
Tags sql client postgresql syntax psql
This article mainly introduces how to run Python applications in the Django framework. Before that, you must set up a simple view and template. The next step is the core content application configuration described in this article, you can refer to the following concepts, fields, and relationships for a friend who needs them:

  • An author has a surname, a famous name, and an email address.
  • The publisher has a name, address, city, province, country, and website.
  • Books have the name and date of publication. It has one or more authors (and the authors are many-to-many associations [connected-to-others]), there is only one publisher (which is a one-to-many association with the publisher, also known as the foreign key [foreign key])

The first step is to describe them using Python code. Open the models. py created by the ''startapp'' command and enter the following content:

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()class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField()class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField()

Let's quickly explain the meaning of these codes. The first thing to note is that every data Model is a subclass of django. db. models. Model. Its parent class Model contains all the necessary methods for interacting with the database, and provides a concise and beautiful syntax for defining database fields. Believe it or not, these are all the code we need to write to access basic data through Django.

Each model is equivalent to a single database table, and each attribute is also a field in this table. The attribute name is the field name. its type (such as CharField) is equivalent to the field type (such as varchar) of the database ). For example, the Publisher module is equivalent to the following TABLE (described in the create table syntax of PostgreSQL ):

CREATE TABLE "books_publisher" ( "id" serial NOT NULL PRIMARY KEY, "name" varchar(30) NOT NULL, "address" varchar(50) NOT NULL, "city" varchar(60) NOT NULL, "state_province" varchar(30) NOT NULL, "country" varchar(50) NOT NULL, "website" varchar(200) NOT NULL);

In fact, as we will show later, Django can automatically generate these create table statements.

The exception to the rule "each database table corresponds to a class" is multi-to-multi-link. In our example model, the Book has a many-to-many field called authors. This field indicates that a Book has one or more authors, but the Book database table does not have the authors field. On the contrary, Django creates an additional table (multiple-to-multiple join tables) to process the ing between books and authors.

See Appendix B for all the field types and model syntax options.

Note that we have not explicitly defined any primary keys for these models. Unless specified separately, Django automatically generates an auto-incrementing Integer Primary key field for each model. each Django model requires a separate primary key.
Model installation

After the code is completed, let's create these tables in the database. To complete this step, activate these models in the Django project. Add the books app to the list of installed applications in the configuration file to complete this step.

Edit the settings. py file again and find the INSTALLED_APPS settings. INSTALLED_APPS tells Django projects which apps are activated. The default value is as follows:

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites',)

Add # temporary comments before the four settings. (These four apps are frequently used. we will discuss how to use them in subsequent chapters ). In addition, comment out the default settings of MIDDLEWARE_CLASSES, because these entries depend on the apps we just commented out in INSTALLED_APPS. Then, add '''mysite. books ''' to the end of ''installed_apps ''. The set content should look like this:

MIDDLEWARE_CLASSES = ( # 'django.middleware.common.CommonMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware',)INSTALLED_APPS = ( # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.sites', 'mysite.books',)

(As we mentioned in setting TEMPLATE_DIRS in the previous chapter, we also need to add a comma at the end of INSTALLED_APPS, because this is a single-element tuples. In addition, the author of this book prefers to add a comma after each tuple element, whether it has only one element or not. This is to avoid forgetting to add commas, and there is no harm .)

'Mysite. Book' indicates the books app we are writing. Each app in INSTALLED_APPS uses the Python path description. the package path is separated by the decimal point.

Now we can create database tables. First, use the following command to verify the validity of the model:

python manage.py validate

The validate command checks whether the syntax and logic of your model are correct. If everything is normal, you will see the 0 errors found message. If an error occurs, check the model code you entered. The error output provides useful error information to help you correct your model.

Once you think your model may be faulty, run python manage. py validate. It helps you capture common model definition errors.

Run the following command to generate the create table statement (if you are using Unix, you can enable syntax highlighting ):

python manage.py sqlall books

In this command line, books is the name of the app. It is the same as running manage. py startapp. After Execution, the output is as follows:

BEGIN;CREATE TABLE "books_publisher" ( "id" serial NOT NULL PRIMARY KEY, "name" varchar(30) NOT NULL, "address" varchar(50) NOT NULL, "city" varchar(60) NOT NULL, "state_province" varchar(30) NOT NULL, "country" varchar(50) NOT NULL, "website" varchar(200) NOT NULL);CREATE TABLE "books_author" ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(40) NOT NULL, "email" varchar(75) NOT NULL);CREATE TABLE "books_book" ( "id" serial NOT NULL PRIMARY KEY, "title" varchar(100) NOT NULL, "publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id") DEFERRABLE INITIALLY DEFERRED, "publication_date" date NOT NULL);CREATE TABLE "books_book_authors" ( "id" serial NOT NULL PRIMARY KEY, "book_id" integer NOT NULL REFERENCES "books_book" ("id") DEFERRABLE INITIALLY DEFERRED, "author_id" integer NOT NULL REFERENCES "books_author" ("id") DEFERRABLE INITIALLY DEFERRED, UNIQUE ("book_id", "author_id"));CREATE INDEX "books_book_publisher_id" ON "books_book" ("publisher_id");COMMIT;

Note:

  • The automatically generated table name is a combination of the app name (books) and the lower-case model name (publisher, book, author. You can refer to Appendix B to rewrite this rule.
  • As we mentioned earlier, Django automatically adds an id primary key for each table. you can reset it.
  • Follow the conventions to add the "_ id" suffix to the field name of the foreign key. You guessed it. this is also customizable.
  • Foreign keys are clearly defined using the REFERENCES statement.
  • These create table statements are adjusted based on your database. in this way, fields such as: (MySQL), auto_increment (PostgreSQL), and serial (SQLite) are automatically generated. The same as integer primary key, the field name is also automatically processed (for example, single quotes are still double quotes ). The output in this example is based on the PostgreSQL syntax.

The sqlall command does not actually create a data table in the database, but prints the SQL statement segment so that you can see what Django will do. If you want to do this, you can copy the SQL statements to your database client for execution, or directly perform operations through the Unix pipeline (for example, ''python manager. py sqlall books | psql mydb ''). However, Django provides a simpler way to submit SQL statements to the database: ''syncdb' command

python manage.py syncdb

After executing this command, you will see something similar to the following:

Creating table books_publisherCreating table books_authorCreating table books_bookInstalling index for books.Book model

The syncdb command is a simple method for synchronizing your model to the database. It checks the database based on the app set in INSTALLED_APPS. if the table does not exist, it creates it. Note that syncdb cannot modify or delete a model to the database. if you modify or delete a model and want to submit it to the database, syncdb does not perform any processing. (For more information, see the "modify database architecture" section at the end of this chapter .)

If you run python manage. py syncdb again, nothing happens because you have not added a new model or app. Therefore, running python manage. py syncdb is always safe because it does not execute SQL statements repeatedly.

If you are interested, take some time to log on to the database server using your SQL Client and check the data table created by Django. You can manually start the command line client (for example, run the ''psql'' command of PostgreSQL) or run the ''python manage. py dbshell ''. this command will automatically detect which command line client to use based on the settings in ''database_server. It is often said that the future comes to the fore.
Basic data access

Once you create a model, Django automatically provides advanced Python APIs for these models. Run python manage. py shell and enter the following content to try:

>>> from books.models import Publisher>>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',...  city='Berkeley', state_province='CA', country='U.S.A.',...  website='http://www.apress.com/')>>> p1.save()>>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',...  city='Cambridge', state_province='MA', country='U.S.A.',...  website='http://www.oreilly.com/')>>> p2.save()>>> publisher_list = Publisher.objects.all()>>> publisher_list[
 
  , 
  
   ]
  
 

These few lines of code have done a lot of work. Here is a simple example:

  • First, import the Publisher model class, through which we can interact with data tables that contain the publishing house.
  • Then, create an instance of the ''Her her'' class and set values of the ''Name, addresses' field.
  • Call the save () method of the object to save the object to the database. Django executes an INSERT statement in the background.
  • Finally, use the ''Her her. objects' attribute to retrieve the Publisher information from the database. this attribute can be considered to contain the Publisher's record set. There are many methods for this attribute. here we first call the ''Her her. objects. all () ''' method to obtain all objects of the ''Her her'' class in the database. Behind the scenes of this operation, Django executes an SQL ''select' statement.

It is worth noting that this example may not be clearly displayed. When you use the Django modle API to create an object, Django does not save the object to the database, unless you call the ''Save () ''method:

p1 = Publisher(...)# At this point, p1 is not saved to the database yet!p1.save()# Now it is.

If you need to create and store objects to the database in one step, use the ''objects. create () ''' method. The following example is equivalent to the previous example:

>>> p1 = Publisher.objects.create(name='Apress',...  address='2855 Telegraph Avenue',...  city='Berkeley', state_province='CA', country='U.S.A.',...  website='http://www.apress.com/')>>> p2 = Publisher.objects.create(name="O'Reilly",...  address='10 Fawcett St.', city='Cambridge',...  state_province='MA', country='U.S.A.',...  website='http://www.oreilly.com/')>>> publisher_list = Publisher.objects.all()>>> publisher_list

Of course, you must try to execute more Django database APIs. However, let's solve some annoying small problems first.

String representation of the added Module

When we print the entire publisher list, we do not get the desired useful information and cannot distinguish the "'object:

System Message: WARNING/2 (
 
  , line 872); backlinkInline literal start-string without end-string.System Message: WARNING/2 (
  
   , line 872); backlinkInline literal start-string without end-string.[
   
    , 
    
     ]
    
   
  
 

We can solve this problem simply by adding a method _ unicode _ () for the Publisher object __(). The _ unicode _ () method tells Python how to display objects in unicode mode. After the _ unicode _ () method is added to the above three models, you can see the effect:

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.name**class 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**

As you can see, the _ unicode _ () method can perform any processing to return the string representation of an object. The _ unicode _ () method of the Publisher and Book objects simply returns their names and titles. The _ unicode _ () method of the Author object is slightly more complex, it concatenates the values of first_name and last_name with spaces and then returns the result.

The only requirement for _ unicode _ () is that it returns a unicode object. if the ''_ unicode _ () ''method does not return a Unicode object, if an integer number is returned, Python will throw a ''typeerror'' error and prompt: "coercing to Unicode: need string or buffer, int found ".

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.