Django summary entry and models

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/LXJRQJ/article/details/87897486

A, django framework

-data

---- display local data

1.,MVC
	M --- model---模型(玩数据)
	V --- View----视图(显示数据)
	C --- controller---控制器(模型和视图交互)
	M全拼为Model,主要封装对数据库层的访问,对数据库中的数据进行增、删、改、查操作。
	V全拼为View,用于封装结果,生成页面展示的html内容。
	C全拼为Controller,用于接收请求,处理业务逻辑,与Model和View交互,返回结果。
电脑: 
	cpu 
	内存 
	硬盘

高内聚 
低耦合

开源:源代码开源 22w行 google
闭源: 苹果系统
2,MVT
	M model
	V view
	T template
M全拼为Model,与MVC中的M功能相同,负责和数据库交互,进行数据处理。
V全拼为View,与MVC中的C功能相同,接收请求,进行业务处理,返回应答。
T全拼为Template,与MVC中的V功能相同,负责封装构造要返回的html。

Second, the configuration of the virtual environment

- 支持第三方的东西
- 电商 支付
- 博客 不会有支付
电脑:
pip install pygame
pip install zhifu
pip install xxx
pip install xx
pip install xx
- 本地环境
	- 安装的东西越来越多
	- 硬盘
	
- 虚拟环境
	电商 ---电商环境- 支付 python
	博客 ----博客环境---xxx python
	- mkvirtualenv -p python3 环境名字
		指定python版本

		mkvirtualenv  环境名字
		使的是你配置的python版本

	- rmvirtualenv 环境的名字	

	- deactivate 退出当前环境  

	- workon 切换环境

Third, create a project

1、创建项目
django-admin startproject xxxx
2、创建应用
python3 manage.py startapp xxx
3、启动服务
python3 manage.py runserver
	忽略大小写
如何关闭打开上个项目
#注册应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'player',
]	
  -  如何创建数据表
  		 - M  
  不在需要写原生的SQL语句 通过面向对象的ORM 

  class Dog: 就把应用名_类名(小写)当做数据表的名字
  	name = xxxx
  	age = xxxx   这些类属性就会当做字段名字
  O  object  对象
  R  relation 关系
  M	 mapping 映射‘
  就是对象翻译原生的sql去执行
  一个model对象 对应的就是一条数据

1,
# generated migration file

2,
	  python3 manage.py makemigrations
  #迁移
	  python3 manage.py migrate
  sqlite
  #进入shell脚本测试环境
   python3 manage.py shell
    添加
    >>> from player.models import Hero
	>>> hero = Hero()
	>>> hero.name = "元歌"
	>>> hero.gender=2
	>>> hero.desc = "很强 牛逼 好(。・∀・)ノ゙嗨呦"
	>>> from datetime import datetime
	>>> hero.create_time= datetime.now()
	>>> hero.save()#相当于执行了insert语句或者update语句
	查询全部
	Hero.objects.all() 相当于执行select *
	查询当个  
	Hero.objects.filter(id=1) 返回列表
	Hero.objects.filter(id=1).first() 去列表第一个
	删除
	hero.delete()
	改
	也是执行save()方法
	V 视图:
		就是函数 函数里面有个参数叫request
		返回值是HttpResponse
	T:模板	
		在你的***项目 新建一个templates文件夹
		注意:在setting里面要配置一下
		BASE_DIR:就是项目路径
		'DIRS': [os.path.join(BASE_DIR, 'templates')],
	后台:管理数据
	给管理数据的人 创建一个账号
	python3 manage.py createsuperuser
	在settings
	LANGUAGE_CODE = 'zh-hans'
	TIME_ZONE = 'Asia/Shanghai'
	在admin.py
		# 注册
		admin.site.register(Hero)
	在model里面写一个
	    def __str__(self):
   			 return self.name

1, create projects, create an application
2, add the application to Setting
3, creating a model
4, generates migrate files and migrate
5, write the view function
6, configuration urls
7, in the view function to query data
8 to create the template folder under the project directory and creating templates
9, the path configuration template Setting
10, in view of the function return render (request, templates, data) directly to
11, the number of template parsing
http://127.0.0.1:8000

Fourth, Admin

1, the Chinese
open test1 / settings.py file, find the language codes, time zone settings, the contents read as follows:

LANGUAGE_CODE = 'zh-hans' #使用中国语言
TIME_ZONE = 'Asia/Shanghai' #使用中国上海时间

2, create an administrator

python manage.py createsuperuser

3, start the server

python manage.py runserver

4, open your browser and enter the address
http://127.0.0.1:8000/admin/

create_time: time of creation
update_time: Updated

isshow whether to display False True

isdelete whether to delete False

position index field

Note: Do not delete the user some data

Do not physically delete some data,

Alipay: pay 500 yuan to delete records

Annual pay statistics:

Label and articles

A label can not have multiple articles
a paper can have multiple labels

King of glory updated. . . . . .
King game

The Day After Tomorrow shelves. . . .
Tencent game

A table articles:

category_id name ID
1 ha 1
2 1 Oh

Classification category

id name

Model design field full of some do not easily change

The hardest point:
1, Design Model
2, to see the impression of notes queries

In the template which href slash and indiscriminate slash

http://127.0.0.1:8000/app04/

http://127.0.0.1:8000/user/1/ plus /

http://127.0.0.1:8000/app04/user/1/ without /

If you choose such models choice inside
the front end of the display field through the object .get_ _display

Query two characteristics:
inert query:
cache:

# Two query single embodiment
DEF Detail (Request, ID):
# A first method to query a human
person = Person.objects.filter (id = id) .first ()

#如果你用这种方法查询的话 ,如果数据不存在 会抛出异常。如果想让你的程序不能奔溃
#需要加一个异常捕获
try:
    person = Person.objects.get(id=id)
except Person.DoesNotExist as e:
    print(e)
return render(request, 'app05/jianli.html', locals())

Limit the query set

Person.objects.all()[0:5]

# Autocorrelation

Province,
the above mentioned id name
1 Henan
2 Hebei

City
the above mentioned id name parent_id
1 1 Zhengzhou City
, Shijiazhuang 1

Area
ID name the parent_id
. 1 Jinshui. 1
2 XXX 2

Solve;
Province
the above mentioned id name parent_id
1 Henan null
2 Hebei null
3 Zhengzhou cities 1
4 Shijiazhuang 2
5 Jinshui 3
6 4 xxx

# Inquiry province
selet * from area where id = null
zone under inquiry Zhengzhou City
selet * from area where id = 3

City in Henan Province query
selet * from area where id = 1

# Default manager model
objects
If you write a objects1 = models.Manager model class in which ()

That model is kind of the default manager fails

all () only queries of people aged 13

When native Manager can not meet your needs, you need to rewrite manager

Manager return two effects:

1, rewrite the query method
2, custom methods

1, MVC
2, MVT
3, ORM
4, virtual environment
5, create projects and applications
6, django general configuration

to sum up:

1, the field and field constraints model
2, and the associated autocorrelation model
3, model query and reverse lookup
4, custom manager
5, option element
6, choice and get_xxx_display ()
the verbose_name = 'user'
# plurality
verbose_name_plural the verbose_name =
# sort
ordering = [ '-id']

db_table = ‘user’

#view:

1, pycharm create a project
2. Configure MySQL
3, positional parameters and keyword arguments

Night work:
1, with its own independent, then sort out all the knowledge points today. The more complete the better. The more
detailed the better must not copied. Write blog
2, pycharm case configuration
3, mysql normal up

HTTP:
Hypertext Transfer Protocol, stateless TCP Socket-based

Request method:

Get Request
https://www.baidu.com/s domain

Post request new
parameters Body body

PUT updates

DELETE Delete

Status Code:
2xx- request was successful
3xx ---- Redirection
4xx ---- Client Error
5xx - Server Error

Request header:
response header:

If the form is not filled, then the expression of action: add the current default address

Login Registration Case:
1, Model: account number, nickname, password, gender, description
2, registration functions, registration is successful jump to the login page
3, login function, the login is successful display specific information about this person

1, how to maintain login state
2, how to achieve the recommended product
Cookie:
exist among browser,
and is based on the domain name safe.
cookie will automatically passed to the server
cookie expires default browser is closed expires
max_age: specify the number of seconds expired
expires: specific expiration date datetime.datetime (2019,2,26)
for the first time: two words into the search orange cookie
section secondary: again website, put the cookie is automatically passed to the background
session:
exist among servers, keep some sensitive information, there is a session database table
its key fact is that there is inside the cookie sessionid
its value using base64 encryption can be decrypted
session depend on cookie. There will be in the cookie session_id
account has 800 yuan:
codes
Clear codes:
clear all session, delete the value in the storage section
request.session.clear ()
clear the session data, delete the entire session in the data store.
request.session.flush ()
deletes the specified key and value in the session, only to delete a key and the corresponding value in the store.
del request.session [ 'key']
request.session.set_expiry(value)

  • If the value is an integer, the session will expire in value seconds without activity.
  • If the value is 0, then the Cookie user session will expire when the user's browser is closed.
  • If the value is None, the session never expires.

ORM concept

Object-Relational Mapping (Object Relational Mapping, referred ORM) to solve for the model is a phenomenon occurring not match each object relational database technology.
Simply put, by using the ORM metadata that describes the mapping between the object and the database, the program objects are automatically persisted to a relational database.
ORM between the business logic layer and the database layer acts as a bridge.

ORM disadvantage

ORM drawback is that the efficiency of the program will be sacrificed to some extent.
ORM with more SQL statements would not have written, and relational database skills related degradation ...

ORM advantage

The main problem ORM solution is to map objects and relationships. It is usually a class and a correspondence table, a record of each instance of the class corresponding to the table, each field corresponding to each attribute category table.
ORM provides a mapping to the database without writing SQL code directly, just as the operation of the object as the data from the database operations.
Let software developers to focus on business logic processing, improve development efficiency.

Field Type

Need to introduce django.db.models bag use, field types are as follows:
*
AutoField: automatic increase IntegerField, usually not specified, Django will automatically create an automatic increase property called id attribute is not specified. (Must fill in the parameters primary_key = True)

* BooleanField:布尔字段,值为True或False。
* 

NullBooleanField: support Null, True, False three values.
*
As CharField (= MAX_LENGTH characters length): string.

	* 

Max_length parameter indicates the maximum number of characters.
*
TextField: large text field, generally used when more than 4000 characters.
*
IntegerField: integer.
*
DecimalField (max_digits = None, decimal_places = None): decimal floating point number.

	* 

Max_digits parameter represents the total number of digits.
*
Parameters decimal_places represent decimal places.
*
FloatField: float.
*
The DateField [auto_now = False, auto_now_add = False]): Date.

	* 

Auto_now parameters indicate each time to save the object, the field is automatically set to the current time, for the "last modified" timestamp, it always uses the current date, the default is false.
*
Parameters auto_now_add means that when an object is first created automatically set to the current time, for the time stamp created, it always uses the current date, the default is false.
*
Parameters auto_now_add and auto_now are mutually exclusive, the combination of errors will occur.
*
TimeField: time parameters with DateField.
*
DateTimeField: date, parameter with the DateField.
*
FileField: file upload field.

from django.db import models

class UserInfo(models.Model):
# 自动创建一个列名为id的且为自增的整数列
username = models.CharField(max_length=32)

class Group(models.Model):
# 自定义自增列
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)

Guess you like

Origin blog.csdn.net/LXJRQJ/article/details/87897486