Django model Tutorial

Django model

Django provides good support for various databases, including: PostgreSQL, MySQL, SQLite, Oracle.

Django provides a unified call API for these databases. We can according to their business needs to choose a different database.

MySQL is the most commonly used database in Web applications. In this section we will introduce Mysql as an example. You can learn more about Mysql basics through our MySQL tutorial.


If you do not install the mysql driver, you can execute the following command to install:

sudo pip install mysqlclient

Database configuration

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

HelloWorld/HelloWorld/settings.py: File Code

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #Or use it mysql.connector.django 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test123', 'HOST':'localhost', 'PORT':'3306', } }


Add a comment here, so you need to add # - * - coding: UTF-8 - * - to the head of the HelloWorld / settings.py file.

The above contains the database name and user information, which corresponds to the database and user settings in MySQL. Django according to this setting, and MySQL in the corresponding database and user link.

Define the model

Create APP

Django stipulates that if you want to use the model, you must 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:

HelloWorld/TestModel/models.py: File Code

# models.py from django.db import models class Test(models.Model): name = models.CharField(max_length=20)



The above class name represents the database table name, and inherited models.Model, class inside the field that represents the data table name (name), the data type by CharField (equivalent to varchar), DateField (equivalent to datetime), max_length Parameter limited length.

Next, find 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
)

Run on the command line:

$ python manage.py migrate   # Create a table structure

$ python manage.py makemigrations TestModel  # Let Django know that we have some changes in our model
$ python manage.py migrate TestModel   # Create a table structure
See a few lines "Creating table ..." words, your data table to create a good.

Creating tables ...
……
Creating table TestModel_test  #We customize the table
……
The table name structure is: application name _ class name (such as: TestModel_test).
Note: Although we do not have a primary key for the table, Django will automatically add an id as the primary key.

Database operation

Next we add the testdb.py file (described below) to the HelloWorld directory and modify urls.py:

HelloWorld/HelloWorld/urls.py:File Code


from django.conf.urls import * from . import view,testdb urlpatterns = [ url(r'^hello$', view.hello), url(r'^testdb$', testdb.testdb), ]


Adding data
Add data need to create
the object, and then execute the save function, the equivalent of SQL in the INSERT:

HelloWorld/HelloWorld/testdb.py: File Code


# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # Database operation def testdb(request): test1 = Test(name='runoob') test1.save() return HttpResponse("<p>Data added successfully!</p>")
Visit http://127.0.0.1:8000/testdb you can see the data to add a successful tips.
The output is as follows:

Data added successfully!

HelloWorld/HelloWorld/testdb.py: File code


# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # Database operation def testdb(request): # Initialize response = "" response1 = "" # Through all the data manager of the model all () to obtain all the data lines, the equivalent of SQL SELECT * FROM list = Test.objects.all()   # Filter is equivalent to WHERE in SQL, you can set the conditional filter results response2 = Test.objects.filter(id=1)    # Get a single object response3 = Test.objects.get(id=1) # Limit the return of the data equivalent to SQL in the OFFSET 0 LIMIT 2; Test.objects.order_by('name')[0:2]   # Data sort Test.objects.order_by("id") # The above method can be used interlock Test.objects.filter(name="runoob").order_by("id") # Output all data for var in list: response1 += var.name + " " response = response1 return HttpResponse("<p>" + response + "</p>")


The output is shown in the following figure:



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


HelloWorld/HelloWorld/testdb.py: File Code


# - * - coding: utf-8 - * -
 
From django.http import HttpResponse
 
From TestModel.models import Test
 
# Database operation
Def testdb (request):
     # Modify one of the id = 1 name field, and then save, the equivalent of SQL in the UPDATE
     Test1 = Test.objects.get (id = 1)
     Test1.name = 'Google'
     Test1.save ()
    
     # Another way
     # Test.objects.filter (id = 1) .update (name = 'Google')
    
     # Modify all columns
     # Test.objects.all (). Update (name = 'Google')
    
     Return HttpResponse ("<p> edit successfully </ p>")

delete data

To delete an object in a database simply call the object's delete () method:

HelloWorld/HelloWorld/testdb.py: File Code


# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test
# Database operation
Def testdb (request):
     # Delete the data for id = 1
     Test1 = Test.objects.get (id = 1)
     Test1.delete ()
    
     # Another way
     # Test.objects.filter (id = 1) .delete ()
    
     # Delete all data
     # Test.objects.all (). Delete ()
    
     Return HttpResponse ("<p> delete success </ p>")


EmoticonEmoticon