Django Project Practice 3-django model

Source: Internet
Author: User
Tags mysql tutorial

http://blog.csdn.net/pipisorry/article/details/45061579

Previous:Django Project Practice 2-django template

Django Model

{Data and logic can be completely separated}

Django supports a variety of databases, including: PostgreSQL, MySQL, SQLite, Oracle. Django provides a unified invocation API for these databases.

1. using MySQL in Django

MySQL is the most commonly used database in WEB applications. The following is an example of Mysql. [MySQL Tutorial]

1) Django requires a MySQL4.0 or higher version. The 3.X version does not support nested subqueries and some other fairly standard SQL statements.

2) You will also need to download and install MySQLdb from http://www.djangoproject.com/r/python-mysql/. If you're using Python3, download mysqldb for Python3 from here.

If you are using Linux, check if your system's Package Manager provides a package called Python-mysql,python-mysqldb,myspl-python or similar.

Note: MySQL Installer is the + bit, but would install both and the binaries bit.

2. using Python3 's own database SQLite

tutorial See [Django Documentation-writing your first Django app, part 1-database Setup]

Database configuration

We found the DATABASES configuration item in the project's settings.py file and modified its information to:

DATABASES = {'    default ': '        ENGINE ': ' Django.db.backends.mysql ',        ' NAME ': ' Test ',        ' USER ': ' Test ',        ' PASSWORD ': ' test123 ',        ' HOST ': ' localhost ',        ' PORT ': ' 3306 ',    }}

It contains the database name and the user's information, which is the same as the corresponding database and user settings in MySQL. Django is connected to the corresponding database and user in MySQL based on this setting.

Define model Creation APP

Django rules that if you want to use a model, you have to create an app. We use the following command to create a Testmodel app:

Python manage.py Startapp Testmodel

The directory structure is as follows:

helloworld|--testmodel|   | --__init__.py|   | --admin.py|   | --models.py|   | --tests.py|   '--views.py

We modified the testmodel/models.py file with the following code:

# models.pyfrom django.db Import Modelsclass Test (models. Model):    name = models. Charfield (MAX_LENGTH=20)

The class name above represents the database name and inherits the models. Model, the field inside the class represents the field (name) in the data table, the data type is Charfield (equivalent to varchar), Datefield (equivalent to DateTime), and the max_length parameter limits the length.

Next, find the Installed_apps in settings.py, as follows:

Installed_apps = (    ' django.contrib.admin ',    ' Django.contrib.auth ',    ' django.contrib.contenttypes ',    ' django.contrib.sessions ',    ' django.contrib.messages ',    ' django.contrib.staticfiles ',    ' Testmodel ',               # Add this item)

Run Python manage.py syncdb on the command line and see the words "Creating table ..." In a few lines, and your data sheet will be created.

Creating tables ..... Creating table Testmodel_test  #我们自定义的表 ...

The table name structure is: The app Name _ class name (for example: testmodel_test).

Note: Although we did not set the primary key for the table in models, Django automatically adds an ID as the primary key.

Database operations

Next we add the testdb.py file in the HelloWorld directory and modify the urls.py:

From django.conf.urls import *from helloworld.view import hellofrom helloworld.testdb Import testdburlpatterns = Patterns ("",        (' ^hello/$ ', hello),        (' ^testdb/$ ', TestDB),)
Add data

Adding data requires creating the object before executing the Save function, which is equivalent to insert in sql:

#-*-Coding:utf-8-*-from django.http import httpresponsefrom testmodel.models import test# database Operation def testdb (request): TES T1 = Test (name= ' w3cschool.cc ') Test1.save () return HttpResponse ("<p> data added successfully! </p> ")

Visit http://192.168.45.3:8000/testdb/to see a hint of the success of the data addition.

Get Data

Django provides several ways to get the contents of a database, as shown in the following code:

#-*-Coding:utf-8-*-from django.http import httpresponsefrom testmodel.models import test# database Operation def testdb (request): # First Initialize response = "RESPONSE1 =" "# Gets all data rows by objects all () of this model manager, equivalent to select * FromList = Test.objects.all () in SQL Filter equivalent to where in SQL, set conditional filter Result Response2 = Test.objects.filter (id=1) # Get a single object response3 = Test.objects.get (id=1) # Limit the returned data to the equivalent of OFFSET 0 limit 2 in SQL; Test.objects.order_by (' name ') [0:2] #数据排序Test. objects.order_by ("id") # The method above can be chained using Test.objects.filter (name= " W3cschool.cc "). Order_by (" id ") # outputs all data for Var in list:response1 + + Var.name +" "Response = Response1return HttpResponse (" & Lt;p> "+ response +" </p> ")

The output looks like this:

Update data

Modify data can use Save () or update ():

#-*-Coding:utf-8-*-from django.http import httpresponsefrom testmodel.models import test# database Operation def testdb (request): # fix Change one of the Id=1 name fields to save, equivalent to UPDATEtest1 in sql = Test.objects.get (id=1) test1.name = ' W3cschool Rookie tutorial ' Test1.save () # Another way #Test. Objects.filter (id=1). Update (name= ' W3cschool rookie tutorial ') # Modify all Columns # Test.objects.all (). Update (name= ' W3cschool rookie tutorial ') Return HttpResponse ("<p> Modify success </p>")
Delete data

Deleting an object in a database simply calls the object's Delete () method:

#-*-Coding:utf-8-*-from django.http import httpresponsefrom testmodel.models import test# database Operation def testdb (request): # Delete Data except id=1 test1 = Test.objects.get (id=1) Test1.delete () # Another Way # Test.objects.filter (id=1). Delete () # Remove All data # Test.objects.all (). Delete () return HttpResponse ("<p> Delete success </p>")

from:http://blog.csdn.net/pipisorry/article/details/45061579


Django Project Practice 3-django model

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.