home PYTHONJAVA
 

Django model

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

Django provides a unified calling API for these databases. We can choose different databases according to our business needs.

MySQL is the most commonly used database for web applications. In this section we will introduce Mysql as an example. You can use the MySQL tutorial on this site. Learn more about the basics of Mysql.

If you don't have the mysql driver installed, you can install it by executing the following command:

sudo pip install mysqlclient

Database configuration

If you don't have the mysql driver installed, you can install it by executing the following command:

???
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 mysql.connector.django 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test123', 'HOST':'localhost', 'PORT':'3306', } }

Chinese comments have been added here, so you need to add # -*- coding: UTF-8 -*- to the header of the HelloWorld/settings.py file.

The above contains the database name and user information, which are the same as the corresponding database and user settings in MySQL. Based on this setting, Django connects to the corresponding database and user in MySQL.


Defining the model

Create an app

Django stipulates that if you want to use a model, you must create an app. We create an app of TestModel using the following command:

django-admin startapp < /span>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 inherits models.Model, the fields in the class represent the fields (name) in the data table, the data type is by CharField (equivalent to varchar), DateField (equivalent to datetime) ), The max_length parameter defines the length.

Next, find the INSTALLED_APPS item 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 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

After seeing a few lines of "Creating table...", your data table is created.

Creatingtables ... 
...
Creating table TestModel_test #Our Custom Table
...

Table name composition structure is: application name_class name (such as: TestModel_test).

Note: Although we didn't set the primary key for the table in models, Django will automatically add an id as the primary key.


Database operations

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), ]

Add data

Adding data requires creating the object first, then executing the save function, which is equivalent to INSERT in SQL:

HelloWorld/HelloWorld/testdb.py: File Code:

# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # Database Operations def testdb(request): test1= Test(name='WELOOKUPS') test1.save() return HttpResponse("<p>Data added successfully!</p> ;")

Visit http://127.0.0.1:8000/testdb to see a prompt for data to be added successfully.

The output is as follows:

Get data

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

HelloWorld/HelloWorld/testdb.py: File Code:

# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # Database Operations def testdb(request): # Initialization response= "" response1= "" # Get all rows of data through the all() function of the model manager, which is equivalent to SELECT in the SQL * FROM list= Test.objects.all() # filter is equivalent to WHERE in SQL, you can set conditional filtering results response2 = Test.objects.filter(id= 1) # Get a single object response3 = Test.objects.get(id= 1) # Limiting the returned data is equivalent to OFFSET 0 LIMIT 2 in SQL; Test.objects.order_by('name') [0:2] #Data Sorting Test.objects.order_by("id") # The above methods can be chained Test.objects.filter(name="WELOOKUPS ").order_by("id") # Output all data for var in list: response1 += var .name + " " response= response1 return HttpResponse("<p>" + response + "</p> ")

Update data

Modify data using save() or update():

HelloWorld/HelloWorld/testdb.py: File Code:

# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # Database Operations def testdb(request): # Modify one of the name fields with id=1, then save, which is equivalent to UPDATE in SQL 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>Modify Success</p>< /span>")

Delete data

To delete an object in the database, just call the delete() method of the object:

HelloWorld/HelloWorld/testdb.py: File Code:

# -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # Database Operations def testdb(request): # Delete 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 successfully</p>< /span>")





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.