Django Overview

Django Overview

Flask Django and belong to the same frame but belonging Django heavyweight frame encapsulates a number of methods, writing the code more compact. Django1.11 will support up to 2020, you first need to install Django

pip install django==1.11.7

create

  1. Using the command line

Create a Project:django-admin startproject ProjectName

Create an application:python manage.py startapp AppName

App created new needs in the main frame in the settings.py INSTALLED_APPSregistered, added to the list ‘AppName’can be.

  1. Use pycharm

Project type selection Django

start up

python manage.py runserver

The default port 8000 to start the machine, if you want to achieve remote access, you need to set in settings.py in ALLOW_HOSTS = ["*"], and then add parameters at startup.

IP and port can be added, or to add a separate port, not only add IP

python manage.py runserver 0.0.0.0:8000
python manage.py runserver 9000

composition

Directory tree as follows:

├── App
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── Django
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   └── settings.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py
  1. manage.py : environmental testing and startup services
  2. AppName: directory is created in our App
    • migrations: migrate files automatically generated
    • app.py : Creating app configuration
    • models.py : Create a database model
    • test.py : write test procedures
    • urls.py : Registration route, imported from the views of the
    • views.py : define the route
  3. The main frame
    • __init__.py: Incoming pymysql module, disguised as MySQLdb
    • settings.py : Register app, templates, databases, and so set the path
    • wsgi.py : communication Client Application and
  4. static: Static file folder

If you use static folder, you need to register static files in a directory inside settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

If you create a Django project in pycharm, the file will be automatically generated Templates plus, used to store the template file, but we can also create a folder labeled Templates folder itself

Database Interaction

Django ORM module frame is built, also built migration system, also built shell, and the shell may bind migration system, complete with the command line more features.

Use the migration system

Django is no need to import the model library to set up inside, while the migration command will automatically create the database

  1. Generated migration file python manage.py makemigrations
  2. Perform the migration file python manage.py migrate

Will be generated in the migration folder inside the migration file, the difference between the amount of updates, if needed for the database to do a lot of change, or delete data table, you need to delete the migration file, and then delete the migration entry library migration table, and then migrate .

Migration system with a lot of shell command, with the python manage.py --helpview command, generally used in the testing and debugging, after completing construction of the model function test database, or reproduce the error.

drive

Django's default database is sqlite, if you are using sqlite, database configuration not need to change, you can customize the database name, if you use other databases require mysql, etc., configured accordingly, here are three mysql database comparison engine

mysqlclient:

For python2,3 support, but there are requirements for the installation of mysql, mysql need to get his driver's profile mysql.cnf

mysql-python:

Only supports python2 does not support python3

pymysql:

Support python2,3, pymysql can be disguised mysqlclient, __init__.py main frame in which the code is added

import pymsql
pymysql.install_as_MySQLdb()

A frame disposed in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'HelloDjango',
        'USER': 'root',
        'PASSWORD': '000000',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}

SNAKE

CRUD database, in addition to creating are based on the query. When creating an object, Django will not directly operate the database, frequently erase the disk, the program will reduce the operating performance, Django will generate an object SQL statements stored in the cache, call the save method, the database will operation.

  1. create

Native Django To create an object class method in the package data model.

@classmethod
def create(cls, name, age):
    user = UserModel.objects.create(u_name=name, u_age=age)
    return user

Then call this method

user = UserModel(u_name='Tom', u_age=23)
user.save()
  1. retrieve

Django default query manager is a objectsquery method

  • filter

    • filter screen out qualified results
    • exclude selected does not meet the criteria
  • get

    • Query conditions
    # Django中不允许字段名中包含双下划线,他的双下划线被用来标记筛选条件中的运算符
    # 在筛选条件中如果需要两个下划线来标记,只是获取字段值需要加引号
    user = UserModel.objects.get(u_age__gt=50).order_by("u_id")
    
    • get a double-edged sword
      • If a match to a precision element, can be returned to normal
      • If there is no match to the results ran DoesNotExist error
      • If a match to more than one result, an error will be thrown MutipleObjectsReturned
    • all
      • All return query results
    • first
      • Does not require conditions, the first query returns a set of elements, i.e., a first data
    • last
      • Conditions do not need to return to query the last element set, the last piece of data
    • count
      • Returns the object focus of the current query number, usually used in conjunction with other queries
    • exist
      • Determine whether the query set has data, return True, otherwise False
  • Limit the query

    • Queries can be used to limit a range to write, before a digital equivalent offset(), the latter figure is equivalent to limit()the subscript can not be negative
    games = Game.objects.filter(g_price__gt=50).filter(g_price__lt=80)
    # offset(2)   limit(3)----5 - 2
    games = games[2, 5]
    
    
  • query properties

    • According to the results of the query, the output of the SQL statement
    games = Game.objects.filter(g_price__gt=50).filter(g_price__lt=80)
    # 打印转换的SQL语句
    print(games.query)
    
  • Comparison Operators

    • Case-sensitive, in front with i(ignore)can be canceled case sensitive
    • exact determination accuracy, case sensitive
      • UserModel.objects.filter(user__u_name__exact='tomm')
    • contains comprising determining whether, case sensitive
      • filter(sname__contains='赵')
    • startwith, endwith value to the beginning or end, case sensitive
      • filter(u_name__startwith='A')
    • in whether included in the scope
      • filter(pk__in=[2, 4, 6, 8])
    • Like like, shaped like, can be matched with a regular
      • filter(u_name__like('vic*')) Beginning with vic
    • gt, gte, lt, lte greater than, greater equal, less than, less than or equal
      • filter(u_age__gt=30)
    • What sort through order_by
      • Plus front element -represented reverse
      • UserModel.objects.get(u_age__gt=50).order_by("u_id")
  • Time Parameters

    • year, month, day, week_day, hour, minute, second
    books = Book.objects.filter(b_publish_date__year=2020)
    
  • Aggregate function

    • Avg mean value
    • Count Statistics
    • Max maximum
    • Minimum Min
    • Sum summation
    # aggregate为获取的集合,在集合中使用聚合函数,求出最大年龄的用户
    UserModel.objects(),aggregate(Max("u_age"))
    
  • F object and the object Q

    • F object, two properties are compared, because there are two conditions must be filtered to underscore mark is legal, if there are two values ​​need to be compared in a query, can not be two double underline at the same time, we need to use F object the legalization of this property, at the same time other arithmetic
    # 用F对象来比较两个属性的大小
    grades = Grade.objects.filter(g_girl_num__gt=F("g_boy_num"))
    # 获取属性后,通过F对象来对属性来进行算数运算
    grades = Grades.object.filter(g_girl_num__gt=F("g_boy_num"+50))
    
    • Q objects, supports and non- critical parameters of the query, for determining the properties of the filter conditions
    # 与:&    或:|    非:~
    # 获取年龄小于25的用户
    UserModel.objects.filter(Q(u_age__lt=25))
    # 获取年龄不小于25的用户
    UserModel.objects.filter(~Q(u_age__lt=25))
    
  1. update

    Based on the query:

    1. Query object
    2. Modify the properties
    3. Object .save ()
  2. delete

    Based on the query:

    1. Query object
    2. To query object
    3. Object .delete

Guess you like

Origin blog.csdn.net/qq_27114273/article/details/92396656