django-admin startproject djangomodel django-admin startapp App python manage.py startapp App
ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'templates') ], DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'GP1djangomodel', 'PORT':'3306', 'HOST':'localhost', 'USER':'root', 'PASSWORD':'mysql', } } LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
import pymysql pymysql.install_as_MySQLdb()
mysql> create database GP1djangomodel charset=utf8; Query OK, 1 row affected (0.17 sec)
python manage.py startapp App
在企業開發中,咱們一般是從數據開始開發的python
使用模型類進行增刪改查(CRUD)操做mysql
ORM(object relational mapping)對象關係映射,是一種程序技術,用於實現面向對象編程語言裏不一樣類型系統的數據之間(數據與數據庫之間)的轉換,能夠簡單理解爲翻譯機,核心思想是解耦,將業務邏輯與數據庫的SQL語句進行解耦sql
graph LR 實體-->ORM ORM-->數據庫
graph LR model-->ORM ORM-->database
將業務邏輯和SQL進行了解耦數據庫
class Meta: db_table=xxx #定義數據表名,推薦使用小寫字母 ordering = [] #對象的默認排序字段,獲取對象列表時使用,一般是integer類型,升序ordering['id'],降序ordering['-id']
from django.db import models # Create your models here. #假裝Django模型 class Person(models.Model): # 約束,用戶名不容許重複 p_name = models.CharField(max_length=16,unique=True) # 默認18歲 p_age = models.IntegerField(default=18,db_column='age') # False 表明男,True表明女,db_column映射 p_sex = models.BooleanField(default=False,db_column='sex') #改表名 class Meta: db_table = 'People'
E:\py27\Django_project\djangomodel>python manage.py makemigrations Migrations for 'App': App\migrations\0001_initial.py - Create model Person E:\py27\Django_project\djangomodel>python manage.py migrate Operations to perform: Apply all migrations: App, admin, auth, contenttypes, sessions Running migrations: Applying App.0001_initial... OK
Django默認經過模型的objects對象實現模型數據查詢
Django有兩種過濾器用於篩選記錄django
多個filter和exclude能夠鏈接在一塊兒查詢編程
模型過濾 * filter * exclude * 連續使用 * 鏈式調用 * Persion.objects.filter(條件).filter(條件).xxx.exclude().exclude()
from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url('admin/', admin.site.urls), url('^App/',include('App.urls')), ]
添加用戶session
#conding:utf-8 from django.conf.urls import url from App import views urlpatterns = [ url(r'^addpersions/',views.add_persions), ]
from django.shortcuts import render,HttpResponse from App.models import Person import random # Create your views here. def add_persions(request): for i in range(15): persion = Person() flag = random.randrange(100) persion.p_name = 'Tom%d' %i persion.p_age = flag persion.p_sex = flag%2 persion.save() return HttpResponse("批量建立成功")
查詢用戶app
#conding:utf-8 from django.conf.urls import url from App import views urlpatterns = [ url(r'^addpersions/',views.add_persions), url(r'getpersions/',views.get_persions), ]
def get_persions(request): persion = Person.objects.filter(p_age__gt=18) context = { "persion":persion } return render(request,'persion_list.html',context=context)
def get_persions(request): persion = Person.objects.filter(p_age__gt=50) context = { "persion":persion } return render(request,'persion_list.html',context=context)
def get_persions(request): persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80) context = { "persion":persion } return render(request,'persion_list.html',context=context)
def get_persions(request): # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80) persion = Person.objects.exclude(p_age__lt=50) context = { "persion":persion } return render(request,'persion_list.html',context=context)
def get_persions(request): # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80) persion = Person.objects.exclude(p_age__lt=50).filter(p_age__lt=80) context = { "persion":persion } return render(request,'persion_list.html',context=context)
def get_persions(request): # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80) persion = Person.objects.exclude(p_age__lt=50).filter(p_age__lt=80) print(type(persion)) context = { "persion":persion } return render(request,'persion_list.html',context=context) System check identified no issues (0 silenced). November 28, 2019 - 11:37:41 Django version 1.11.26, using settings 'djangomodel.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <class 'django.db.models.query.QuerySet'> #不是列表,可是可迭代 [28/Nov/2019 11:37:41] "GET /App/getpersions/ HTTP/1.1" 200 478 <class 'django.db.models.query.QuerySet'> [28/Nov/2019 11:37:43] "GET /App/getpersions/ HTTP/1.1" 200 478
def get_persions(request): # persion = Person.objects.filter(p_age__gt=50).filter(p_age__lt = 80) persion = Person.objects.exclude(p_age__lt=50).filter(p_age__gt=80) print(type(persion)) persiontwo = Person.objects.filter(p_age__in=[40,30,47]) print(type(persiontwo)) context = { "persion":persion, "persiontwo":persiontwo } return render(request,'persion_list.html',context=context)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>persion_list</title> </head> <body> <h3>PersionList</h3> <ul> {% for persion in persion %} <li>姓名:{{ persion.p_name }} 年齡:{{ persion.p_age }}</li> {% endfor %} </ul> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>persion_list</title> </head> <body> <h3>PersionList</h3> <ul> {% for persion in persion %} <li>姓名:{{ persion.p_name }} 年齡:{{ persion.p_age }}</li> {% endfor %} </ul> <ul> {% for persiontwo in persiontwo %} <li>姓名2:{{ persiontwo.p_name }} 年齡2:{{ persiontwo.p_age }}</li> {% endfor %} </ul> </body> </html>
目的:向數據庫中添加數據dom
當建立對象時,Django不會對數據庫進行讀寫操做,當調用save()方法時才與數據庫交互,將對象保存到數據庫中
注意:__init__已經在父類models.Model中使用,在自定義的模型中沒法使用
建立對象方案:
在模型類中增長類方法去建立對象 @classmethod def create(cls,name,age): 在自定義的管理器中添加方法來建立對象
#conding:utf-8 from django.conf.urls import url from App import views urlpatterns = [ url(r'^addpersions/',views.add_persions), url(r'getpersions/',views.get_persions), url(r'^addperson',views.add_person), ]
def add_person(request): person = Person.objects.create(p_name = '小明',p_age = 15,p_sex=True) person.save() return HttpResponse('小明建立成功')
方法
from django.db import models # Create your models here. #假裝Django模型 class Person(models.Model): # 約束,用戶名不容許重複 p_name = models.CharField(max_length=16,unique=True) # 默認18歲 p_age = models.IntegerField(default=18,db_column='age') # False 表明男,True表明女,db_column映射 p_sex = models.BooleanField(default=False,db_column='sex') p_hobby = models.CharField(max_length=32,null=True,blank=True) #改表名 @classmethod def create(cls,p_name,p_age=100,p_sex=True,p_hobby='gaming'): return cls(p_name=p_name,p_age=p_age,p_hobby=p_hobby) class Meta: db_table = 'People'
def add_person(request): # person = Person.objects.create(p_name = '小明',p_age = 15,p_sex=True) # person.save() # person = Person(p_age=28) # 是"" None Null 不能重寫__init__ 能夠經過其餘手段,實現屬性自定義賦值 person = Person.create('jack') person.save() return HttpResponse('建立成功')