(transfer) Django model (3)

Reprinted from: http://www.runoob.com/django/django-model.html

 

Django provides good 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 in web applications. In this chapter, we will introduce Mysql as an example. You can  learn more about the basics of Mysql through the  MySQL tutorial on this site.

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

sudo pip install mysqlclient

Note: pip command execution does not work on Windows. You can execute python pip.exe mysqlclient under /python/scripts. However, the installation may not be successful due to network reasons. So it can be found on the following website: http://www.lfd.uci.edu/~gohlke/pythonlibs/#

Find the mysqlclient installation package installation.

One thing to note: 
the following are all versions of mysqlclient retrieved from this site

Mysqlclient, a fork of the MySQL-python interface for the MySQL database.

    mysqlclient-1.3.9-cp27-cp27m-win32.whl
    mysqlclient-1.3.9-cp27-cp27m-win_amd64.whl
    mysqlclient-1.3.9-cp34-cp34m-win32.whl
    mysqlclient-1.3.9-cp34-cp34m-win_amd64.whl
    mysqlclient-1.3.9-cp35-cp35m-win32.whl
    mysqlclient-1.3.9-cp35-cp35m-win_amd64.whl
    mysqlclient-1.3.9-cp36-cp36m-win32.whl
    mysqlclient-1.3.9-cp36-cp36m-win_amd64.whl

cp35 represents the version of python3.5, and win32 represents the 32-bit system, so you need to choose the correct one, otherwise the installation process will report an error that the platform does not match.

 

How to install: Copy the installation package into the python/scripts directory, and enter the command: python pip.exe install ./installation package name

The installation is complete.

 

Database configuration

We find the DATABASES configuration item in the settings.py file of the project and modify its information to:

HelloWorld/HelloWorld/settings.py: File code:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Or use mysql.connector.django
        'NAME': 'test', #Note that you need to create a database in DB before you can use it , or report that the database cannot be found
        'USER': 'test',
        'PASSWORD': 'test123',
        'HOST':'localhost',
        'PORT':'3306',
    }
}

Chinese comments are added here, so you need to add  # -*- coding: UTF-8 -*- at the head 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 with the corresponding database and user in MySQL.


Define the model

Create an app

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

django-admin.py startapp TestModel

The directory structure is as follows:

HelloWorld | --TestModel || - __init__.py
||-- admin.py
||-- models.py
||-- tests.py
|`-- views.py

We modify the TestModel/models.py file, the code is as follows:

HelloWorld/TestModel/models.py: File code:

# models.py
fromdjango.dbimportmodels

classTest(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 in the data table (name), and the data types are CharField (equivalent to varchar), DateField (equivalent to datetime), max_length The parameter limits 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)

Run at the command line:

$ python manage.py migrate # Create table structure

$ python manage.py makemigrations TestModel # Let Django know we have some changes in our model
$ python manage.py migrate TestModel # create table structure

******如果执行manage.py migrate 报错:can't load myqsl modules很可能就是没安装mysqlclient,需要按上文安装。

 

看到几行 "Creating table…" 的字样,你的数据表就创建好了。

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

表名组成结构为:应用名_类名(如:TestModel_test)。

注意:尽管我们没有在models给表设置主键,但是Django会自动添加一个id作为主键。


数据库操作

接下来我们在 HelloWorld 目录中添加 testdb.py 文件(下面介绍),并修改 urls.py:

HelloWorld/HelloWorld/urls.py: 文件代码:

fromdjango.conf.urlsimport *
from . importview,testdb

urlpatterns = [
    url(r'^hello$', view.hello),
    url(r'^testdb$', testdb.testdb),
]

添加数据

添加数据需要先创建对象,然后再执行 save 函数,相当于SQL中的INSERT:

HelloWorld/HelloWorld/testdb.py: 文件代码:

# -*- coding: utf-8 -*-

fromdjango.httpimportHttpResponse

fromTestModel.modelsimportTest

# 数据库操作
deftestdb(request):
    test1 = Test(name='runoob')
    test1.save()
    returnHttpResponse("<p>数据添加成功!</p>")

访问 http://127.0.0.1:8000/testdb 就可以看到数据添加成功的提示。

输出结果如下:

获取数据

Django提供了多种方式来获取数据库的内容,如下代码所示:

HelloWorld/HelloWorld/testdb.py: 文件代码:

# -*- coding: utf-8 -*-

fromdjango.httpimportHttpResponse

fromTestModel.modelsimportTest

# 数据库操作
deftestdb(request):
    # 初始化
    response = ""
    response1 = ""
   
   
    # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM
    list = Test.objects.all()
       
    # filter相当于SQL中的WHERE,可设置条件过滤结果
    response2 = Test.objects.filter(id=1)
   
    # 获取单个对象
    response3 = Test.objects.get(id=1)
   
    # 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
    Test.objects.order_by('name')[0:2]
   
    #数据排序
    Test.objects.order_by("id")
   
    # 上面的方法可以连锁使用
    Test.objects.filter(name="runoob").order_by("id")
   
    # 输出所有数据
    forvarinlist:
        response1 += var.name + ""
    response = response1
    returnHttpResponse("<p>" + response + "</p>")

更新数据

修改数据可以使用 save() 或 update():

HelloWorld/HelloWorld/testdb.py: 文件代码:

# -*- coding: utf-8 -*-

fromdjango.httpimportHttpResponse

fromTestModel.modelsimportTest

# 数据库操作
deftestdb(request):
    # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
    test1 = Test.objects.get(id=1)
    test1.name = 'Google'
    test1.save()
   
    # 另外一种方式
    #Test.objects.filter(id=1).update(name='Google')
   
    # 修改所有的列
    # Test.objects.all().update(name='Google')
   
    returnHttpResponse("<p>修改成功</p>")

删除数据

删除数据库中的对象只需调用该对象的delete()方法即可:

HelloWorld/HelloWorld/testdb.py: 文件代码:

# -*- coding: utf-8 -*-

fromdjango.httpimportHttpResponse

fromTestModel.modelsimportTest

# 数据库操作
deftestdb(request):
    # 删除id=1的数据
    test1 = Test.objects.get(id=1)
    test1.delete()
   
    # 另外一种方式
    # Test.objects.filter(id=1).delete()
   
    # 删除所有数据
    # Test.objects.all().delete()
   
    returnHttpResponse("<p>删除成功</p>")

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326268023&siteId=291194637