Django--Model (database layer)

Source: Internet
Author: User

In Web applications, subjective logic (view processing) often involves interaction with the database. The database-driven Web site connects to the database in the background, fetching data from it, and then throwing a nice interface over the web. Many complex websites offer a combination of the above two functions (such as Amazon.com), while Python is born with a simple and powerful way to execute database queries, which is ideal for developing such database-driven Web sites.

He is the Django database layer described below!

"Hard-coded link database"

Cat ~/helloworld/helloworld/view.py

From django.shortcuts import render_to_responseimport mysqldbdef book_list (Request): db = MySQLdb.connect (user= ' me ', db = ' MyDB ', passwd= ' secret ', host= ' localhost ') cursor = Db.cursor () cursor.execute (' SELECT name from books ORDER by Nam E ') names = [row[0] for row in Cursor.fetchall ()] Db.close () return render_to_response (' book_list.html ', {' names ': NA MES})

Cons: Although this method is available, but we have the parameter configuration directly hard-coded to the view function, obviously made the first two sections of the same error; If we change a parameter, change a database, change the execution of the statement and so on, will cause a wide range of changes.

So can we create a template as in the previous section, in fact Django provides a much simpler and straightforward way: the database API

===============================================================================================

MVC architecture Model, MTV development model

The Django design follows the loose coupling principle, and modifying a part does not affect the rest. In the view function, the template system separates the business logic from the presentation logic, and so is the database layer.

MVC schema pattern: A combination of data access logic (model), Performance logic (view), Business logic (Controller)

Where C is handled by the framework itself, Django is more concerned with the model, template, view (views), also known as the MTV framework

M: Data access, processing all transactions related to data;

T: Presentation layer, dealing with performance-related decisions, such as how the page is displayed;

V: The view, the logic that processes the access model and the template, can be seen as a bridge between the model and the template.

Note: Django thinks the view is used to show the data, how the controller is presented, and the other frameworks think that the controller is used to present the data, and the view determines how it unfolds.

================================================================================================

The above-mentioned database API, in fact, is to change the Django configuration file, through the configuration file interface into the database.

database database_engine adapter
postgresql http://www.djangoproject.com/ r/python-pgsql/1/
postgresql postgresql_psycopg2 http://www.djangoproject.com/r/python-pgsql/
mysql mysql http://www.djangoproject.com/r/python-mysql/
http://www.djangoproject.com/r/python-sqlite/
oracle http://www.djangoproject.com/r/python-or acle/
Vim ~/helloworld/helloworld/settings.pydatabases = {' default ': {' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' Django ', ' USER ': ' Django ', ' PASSWORD ': ' django123 ', ' HOST ': ' localhost ', ' PORT ': ' 3306 ',}}

Then go to the database to build a Django library and assign a value to the Django user. Then test it (no error message is configured successfully, and can link to MySQL's Django Library, for Django error information, please refer to the next section):

Launch Shell interface: Python manage.py shell

>>> from django.db Import connection

>>> cursor = Connection.cursor ()

"App app and model model.py"

First App

Django Rules: If you use a Django database layer (or model), you have to create a Django app that puts the model in it and the app app is part of the project.

Python manage.py startapp Mysql_django #创建mysql_django app

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/8B/E8/wKioL1hcETyAMEeSAAAWixnqf4s271.png "title=" 1.png " alt= "Wkiol1hcetyameesaaawixnqf4s271.png"/>

Create a good app to add apps to HelloWorld project

Vim ~/helloworld/helloworld/settings.pyinstalled_apps = [' django.contrib.admin ', ' Django.contrib.auth ', ' Django.contrib.contenttypes ', ' django.contrib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', * * ' Mysql_django ', #逗号结尾, also available point syntax Helloworld.mysql_django]

First model

In fact, the Django model is the Python code that describes the table structure in the database

Vim ~/helloworld/mysql_django/models.pyfrom django.db import modelsclass publisher ( Models. Model):  #CREATE  TABLE  "Books_publisher" ("id"  serial NOT NULL PRIMARY  Key,    name = models. Charfield (max_length=30)    # "name"  varchar ( NOT NULL,   ) Address = models. Charfield (MAX_LENGTH=50)  # "Address"  varchar ( not null,   city =)  models. Charfield (max_length=60)     # "City"  varchar  NOT NULL,    State_province = models. Charfield (max_length=30)  # "State_province"  varchar ( not null,   country)  = models. Charfield (max_length=50)  # "Country"  varchar ()  not null,   website =  models. Urlfield ()         # "website"  varchAR (+)  NOT NULL );                         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 ()

Code interpretation:

1, first, each data model is a subclass of Django.db.models.Model, the parent model contains all the necessary methods to interact with the database;

2, each model is equivalent to a database table, each property is a field, type (Charfield) equivalent to the field type (varchar)

3, publisher example, the Python syntax is equal to the right of the database syntax.

4, the definition of publishers, authors, books, some of the content.

When the above model is completed, and the app is added to the project, it's time to start building the table.

A, check for syntax errors (django1.9.0 version below with Python manage.py validate)

Python manage.py Check

b, build the Database migration file (in the app under the migrations to generate 0001 files, after the change to execute, build 0002 .... migrating files)

Python manage.py makemigrations Mysql_django

C, synchronous database (old version with Python manage.py syncdb, that is, the migration file conversion syntax synchronization database [library Name App Name _ class name])

Python manage.py Migrate

D, convert to SQL language (old version python manage.py Sqlall mysql_django, view converted MySQL syntax)

Python manage.py sqlmigrate Mysql_django 0001

"Python and Database API"

Entry: Python manage.py shell

>>> from mysql_django.models import Publisher #导入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 () #调用了save () method to actually insert P1 into the database

>>> P2 = Publisher.objects.create (name= "O ' Reilly",

... address= ' Fawcett St. ', city= ' Cambridge ',

... state_province= ' MA ', country= ' U.S.A. ',

Website= ' http://www.oreilly.com/') #objects. Create () method to insert data directly into the database

>>> publisher_list = Publisher.objects.all () #从数据库取出出版商信息 ==select

>>> publisher_list

[<publisher:publisher Object>, <publisher:publisher Object>]


After inserting two data, the reasoned Publisher.objects.all () method takes out the object of the Publisher class, but does not get useful information;

Fix this problem: To add a __unicode__ () method to a Publisher object, he tells Python to display the object in Unicode, as follows:

vim ~/helloworld/mysql_django/models.pyfrom django.db  Import modelsclass publisher (models. Model):      name = models. Charfield (max_length=30)      ......................      Website = models. Urlfield () **      def __unicode__ (self):* *        return self.nameclass author (models. Model):      .........................**    def __unicode__ ( Self):* *       return u '%s %s '  %  (Self.first_name,  self.last_name) **class book (models. Model):      .........................**    def __unicode__ ( Self):* *       return self.title 

============================================================================================

A Unicode object is a python string that can handle millions of different classes of strings. Ordinary python strings are encoded, and a common??? can occur when the calls are interleaved. such as messy characters, this is the problem of coding, and Unicode object is not encoded, use it can not consider the problem of coding. So make sure that each model defines the __UNICODE__ () method.

About unicode:http://www.joelonsoftware.com/articles/unicode.html

Go inside the shell interpreter again, test:>>> publisher_list

[<publisher:apress>, <publisher:o ' reilly>]

============================================================================================

1, data viewing, filtering operations:

>>> Publisher.objects.filter (name= ' Apress ')
[<publisher:apress>] #filter = = where name= ' Apress '
>>> Publisher.objects.filter (country= "U.S.A.", state_province= "CA")
[<publisher:apress>] #逗号转换成了 and
>>> Publisher.objects.filter (name__contains= "Press")
[<publisher:apress>] #__contains = where name like '%press% ';
>>> Publisher.objects.get (name= "Apress")
<Publisher:Apress> #get () method gets a single object, and the filter () function returns a Recordset (list)

(icontains[-like], Startwith/endswith, Range[between])


2, Data sorting operations:
>>> Publisher.objects.order_by ("name")
[<publisher:apress>, <publisher:o ' reilly>] #按字母排序
>>> Publisher.objects.order_by ("State_province", "address")
[<publisher:apress>, <publisher:o ' reilly>] #第一个字段相同, sort by second
>>> Publisher.objects.order_by ("-name")
[<publisher:o ' Reilly>, <publisher:apress>] #-, indicating reverse ordering

Vim ~/helloworld/mysql_django/models.py class Publisher (models. Model): def __unicode__ (self): Return self.name** class Meta: * * ordering = [' name '] #Meta类, default is sorted by the name field

3, Chain inquiry:
>>> Publisher.objects.filter (country= "U.S.A."). Order_by ("-name")
[<publisher:o ' Reilly>, <publisher:apress>] #检索country = "U.S.A." Descending arrangement
>>> Publisher.objects.order_by (' name ') [0:2] #取数据的特定子集 =offset 0 limit 2, query statements can also be added
>>> Publisher.objects.order_by (' name ') [0] #[0]=limit 1; negative index [-1] is not supported, but can be implemented in descending order [0]
<Publisher:Apress>


4. Add change operation: (name, save, ID, update)

Add data:>>> P3 = .... name= ' Apress ' ...

Get data:>>> P2 = Publisher.objects.get (name= "Apress")

Change data:>>> p2.name = ' Apress publishing '

Save Data:>>> P2.save () #他会update此id全部字段, not just the name field, but also the method of lightweight change.

See the primary key id:>>> p2.id #我们可根据get到的数据查id, you can also directly into the database to check

Change Data:>>> Publisher.objects.filter (id=1). Update (name= ' Apress publishing ')

Bulk Change:>>> Publisher.objects.all (). Update (country= ' USA ') #返回数值即更改的条数

5. Delete command operation:

Get data:>>> p = Publisher.objects.get (name= "O ' Reilly") #先得到数据再删除

Delete Data:>>> p.delete ()

Delete:>>> Publisher.objects.filter (country= ' USA ') directly. Delete () #删除所有country = ' USA '

Delete all:>>> Publisher.objects.all (). Delete () #不加all () method cannot delete

View Data:>>> Publisher.objects.all ()


Of course, the above operations are done directly in the shell interpreter, we can also write to the view function, the page view.

-------------------------------------------------------------------------------------------------





This article is from the "North Ice--q" blog, please be sure to keep this source http://beibing.blog.51cto.com/10693373/1885340

Django--Model (database layer)

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.