Django Web Development Study notes (5)

Source: Internet
Author: User

Part V Model Layer

Create an app project. The difference between app and project reference Djangobook is:

A project contains a number of Django apps and their configuration.

Technically, project's role is to provide configuration files, such as where to define database connection information, the list of installed apps, Template_dirs , and so on.

An app is a set of Django features, often including models and views, in the way Python's package structure exists.

For example, Django itself has some apps, such as a comment system and an automated management interface. One key point of the app is that they are easily ported to other project and reused by multiple project.

First, create the app package

Python manage.py startapp yourappname [yourappdestination]

Take a look at the name of the default generated file:

Yourappname--------

--------__init__.py

--------admin.py

--------models.py

--------tests.py

--------views.py

We talked about it earlier. The M representation model in MTV. The Django model is defined in the database as data expressed in Python code form. It is equivalent to the CREATE TABLE statement for the data layer, except that it executes Python code instead of SQL and contains more meaning than the database field definition. Django uses the model to execute SQL code in the background and describe the results in Python data structures. Django also uses models to present high-level concepts that SQL cannot handle. (Djangobook)

Introspection (automatic database recognition at runtime) can lead to overloading and data integrity issues. To provide a convenient data access API, Django needs to somehow know the information inside the database layer in two ways. The first approach is to explicitly define the data model in Python, and the second is to automatically detect the recognition data model through introspection.

The second way looks clearer because the data table information is stored in only one place-the database, but it can cause some problems. First, the runtime scans the database for serious system overloads. If each request is to scan the database's table structure, or even when the service is started, it can cause unacceptable system overloads. (some argue that this level of system overload is acceptable, and that the Django developer's goal is to minimize the system overload of the framework). Second, some databases, especially the older versions of MySQL, do not fully store those exact introspection metadata.

It's interesting to write Python code, and keeping your thinking in Python will prevent your brain from switching back and forth in different areas. Keeping it as simple as possible in a single programming environment/mindset can help you increase productivity. Have to repeat SQL, write Python code, and then write SQL, ..., will make your head cracked.

The data model is expressed in code so that you can easily versioning them. In this way, you can easily understand the changes in the data layer.

SQL can only describe a specific type of data field. For example, most databases do not have a dedicated field type to describe email addresses, URLs. And with a Django model you can do that. The advantage is that advanced data types bring higher efficiency and better code reuse.

SQL also has compatibility issues with different database platforms. When publishing a web app, using a Python module to describe the database structure information avoids writing different CREATE TABLEfor MySQL, PostgreSQL, and SQLite.

Second, create the model

Open model.py and add the following statement:

From django.db import models# Create your models Here.class Student (models. Model):    name = Models.charfield (max_length=30)    address = Models.charfield (max_length =) City    = Models.charfield (max_length=30)    grade = Models.charfield (max_length =)    website = models. Urlfield () class School (models. Model):    name = Models.charfield (max_length=30) City    = models. Manytomanyfield (Student)    createdate = models. Datefield ()

This is similar to the statement that creates a table in SQL. Charfield can be understood as a varchar () field in a database. It is also important to note that there are several special data structures in table school:

Manytomanyfield (Student).

The exception to the rule "each database table corresponds to a class" is a many-to-many relationship. School has a many-to-many field called Student . This field indicates that a school can have many students, and Django creates an extra table (a many-to-many join table) to handle this mapping relationship.

Finally, it is important to note that we do not explicitly define any primary keys for these models. Unless you specify otherwise, Django automatically generates a self-growing integer primary key field for each model each Django model requires a separate primary key. That is, the ID of each record.

Three, model installation

How do we connect our app to project after we've created the app? As we can see above, project's role is to provide the configuration file and install the app. So we could guess that it was placed under the __setting__ directory that was automatically generated when the project was created.

Edit the settings.py file again to find the Installed_apps settings. Installed_apps tells the Django project which apps are active.

Installed_apps = (    ' django.contrib.admin ',    ' Django.contrib.auth ',    ' django.contrib.contenttypes ',    ' django.contrib.sessions ',    ' django.contrib.messages ',    ' django.contrib.staticfiles ',)

We add the following code to this tuple data:

' Djangoe_1.formetc '

We can create the table below. Before creating a table, we should check the validity of the model and execute

Python manage.py Validate

The result of the execution is: 0 error found indicates that the model created is correct

After creating the model successfully, we generate the SQL table and execute

Python manage.py Sqlall Yourappname

The execution result output is as follows:

As we can see, the output structure is the SQL statement form of the model we created. Note The School_city mapping table that is generated in the middle. Is the mapping relationship table that we generated when we mentioned the Manytomany structure. are associated with school_id and student_id as fields respectively.

The sqlall command does not actually create a data table in the database, just prints out the SQL statements so you can see what Django will do. If you want to do this, you can copy those SQL statements to your database client execution, or directly from 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

This command synchronizes the SQL statement you created into your database

We created a database to create a super user.

Iv. Access to Data

Execute command:Python manage.py Shell


2, under this command, we can use the Python statement to delete the table and other tasks, the completion of these tasks are the Django provided API completed. As follows:

Import Yourappname.models as K

T1 = k.student (name= ' YWC ', city= ' Beijing ', grade= ' Master ')

T1.save ()

t2= k.student (name= ' wcy ', city= ' Beijing ', grade= ' doctor ')

T2.save ()

This completes the task of inserting the table, and it is important to note that the data can be inserted successfully only when the. Save () is run.

Let's look at the execution results for each code:

It is important to note that we do not perform any operations on the table when we initialize the table, but only when we do save (), we are similar to executing the INSERT statement in SQL, inserting the initialized data into the table

3, summarize the above operation, we have learned the creation of the table, insert, below we learn to choose, that is, filter operation:

Table name + objects.filter (* *). Similar to the where statement operation.

4. Deleting objects

: It is important to note that objects returned through the Get method have several things that we can only delete through the filter. It looks like the Get method can only get a single object. If you want to delete the entire object you can call the T.student.objects.all (). Delete () function directly

The next chapter we describe how to manage the site operation!

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.