昨日內容回顧
- 外鍵字段的增刪改查
# 一對一 一對多
增:
先查詢數據的對象
publish=跟對象
publish_id=具體的id值
# 多對多
1. 先有數據的對象
2. 使用對象點外鍵字段
# 增
add(1, 2, 3)
add(obj1, obj2, obj3)
# 改
set([1, 2, 3])
set([obj1, obj2, obj3])
# 刪
remove(1, 2)
# 清除
clear()
- 正反向查詢
1. 正向
2. 反向
'''
判斷依據就是看外鍵字段在哪里?
如果外鍵字段在我手里,我查你就是正向
如果外鍵字段不再我手里,我查你就是反向查詢
'''
# 1. 正向查詢按字段(外鍵字段)
# 2. 反向查詢按表名小寫(或者添加 _set.all())
- 基于對象的跨表查詢
# 子查詢
1. 判斷是誰查誰
2. 判斷正向還是反向
3. 根據正反向查詢的依據執行代碼
- 基于雙下劃線的查詢
# 一條SQL語句解決
.values('')
# 連表操作
inner join left join right join union
- F和Q查詢
# F查詢是可以拿到字段的原始數據值
update t set price = price + 100, where id=1;
from django.db.models import F
res = Book.objects.update(price=F('price')+100)
# F默認操作的是數字類型的,對于字符串的話,不能直接使用
from django.db.models.functions import Concat
from django.db.models import Value
res = Book.objects.update(title=Concat(F('title'), Value('aaaa')))
# Q查詢
Q查詢支持3種方式
1. and
2. or
3. 非
filter(Q(price__gt=100), Q(id=1)) # and 關系
filter(Q(price__gt=100) | Q(id=1)) # or 關系
filter(~Q(price__gt=100), ~Q(id=1)) # 非 關系(取反)
# Q的高級查詢
q = Q()
q.connector='OR'
q.children.append(('title', 'aaa'))
q.children.append(('price__gt', 200))
res = models.Book.objects.fileter(q)
print(res)
今日內容概要
- 聚合查詢和分組查詢
- 事務
- ORM中常用的參數
- choices參數
- 批量增加數據
- 多對多的三種創建方式
- Ajax的基本使用
- Ajax提交文件數據
內容詳細
1. 聚合查詢
# 數據準備同上期
# 聚合查詢關鍵字:aggregate
# 在tests.py文件中測試:
# 聚合查詢
from django.db.models import Max, Min, Sum, Count, Avg
# 1.查詢數據中價格最高的
# SQL語句:select max(price) from book
# orm中使用聚合查詢關鍵字:aggregate
# res = models.Book.objects.aggregate(Max('price'))
# res1 = models.Book.objects.aggregate(max_price=Max('price')) # 起別名
# print(res) # {'price__max': Decimal('600.00')}
# print(res1) # {'max_price': Decimal('600.00')}
# 2.查詢所有書籍的總價格
# SQL語句:select sum(price) as sum_price from book # 起別名 as sum_price
# SQL語句:select sum(price) as sum_price, min(price) as min_price from book # 查詢多個數據分別起別名
# res = models.Book.objects.aggregate(sum_price=Sum('price'))
# print(res) # {'sum_price': Decimal('1511.00')}
# 3.查詢所有書籍的平均價格
# SQL語句:select avg(price) as avg_price from book
# res = models.Book.objects.aggregate(avg_price=Avg('price'))
# print(res) # {'avg_price': 377.75}
# 4.一起使用
# res = models.Book.objects.aggregate(max_price=Max('price'), min_price=Min('price'), sum_price=Sum('price'), avg_price=Avg('price'))
# print(res) # {'max_price': Decimal('600.00'), 'min_price': Decimal('211.00'), 'sum_price': Decimal('1511.00'), 'avg_price': 377.75}
2. 分組查詢
# 關鍵字:group by
select * from t group by price, title,
'''分組之后只能拿到分組的依據'''
1. group_concat: 分組之后用
2. concat: 分組之前使用
3. concat_ws:
select concat(title,":",age,":", gender,":") from t
select concat_ws(':', title, age, gender) from t;
# 在tests.py文件中測試:
# ORM中使用分組關鍵字:annotate
# 1.統計每一本書的作者個數
# res = models.Book.objects.annotate() # 代表按照書籍分組
# res = models.Book.objects.annotate(author_num=Count('authors__pk')).values('title', 'author_num')
# print(res) # <QuerySet [{'title': '西游記', 'author_num': 1}, {'title': '西游記1', 'author_num': 1}, {'title': '紅樓夢', 'author_num': 2}, {'title': '三國演義', 'author_num': 2}]>
# 2.統計每個出版社出版的最便宜的書的價格
# res = models.Publish.objects.annotate(min_price=Min('book__price')).values('name', 'min_price')
# print(res) # <QuerySet [{'name': '北京大學出版社', 'min_price': Decimal('300.00')}, {'name': '清華大學出版社', 'min_price': Decimal('211.00')}, {'name': '武漢大學出版社', 'min_price': Decimal('400.00')}]>
# 3.統計不止一個作者的書
# 01 先查詢出每本書的作者個數
# 02 再篩選掉小于等于一的
# res = models.Book.objects.annotate(author_num=Count('authors__pk')).values('title', 'author_num')
# print(res) # <QuerySet [{'title': '西游記', 'author_num': 1}, {'title': '西游記1', 'author_num': 1}, {'title': '紅樓夢', 'author_num': 2}, {'title': '三國演義', 'author_num': 2}]>
# res1 = models.Book.objects.annotate(author_num=Count('authors__pk')).filter(author_num__gt=1).values('title', 'author_num')
# print(res1) # <QuerySet [{'title': '紅樓夢', 'author_num': 2}, {'title': '三國演義', 'author_num': 2}]>
# 4.查詢各個作者出的書的總價格
# res = models.Author.objects.annotate(sum_price=Sum('book__price')).values('name', 'sum_price')
# print(res) # <QuerySet [{'name': 'beijing', 'sum_price': Decimal('700.00')}, {'name': 'qinghua', 'sum_price': Decimal('1211.00')}, {'name': 'wuhan', 'sum_price': Decimal('600.00')}]>
3. 事務
# 作用:保證數據安全
'''
面試題:
四大特性:ACID
事務的隔離級別
'''
# 1. 開啟事務:
start transaction;
# 2. 提交事務
commit;
# 3. 回滾事務
rollback;
# 在tests.py文件中測試:
"""通過django開啟事物"""
from django.db import transaction
try:
# 執行的SQL語句
with transaction.Atomic:
# sql語句
# sql語句
# 寫在里面都屬于同一個事物
pass
except Exception as e:
print(e)
transaction.rollback()
4. ORM中常用字段和參數
4.1 ORM字段
AutoField
int自增列,必須填入參數 primary_key=True。當model中如果沒有自增列,則自動會創建一個列名為id的列。
IntegerField
一個整數類型,范圍在 -2147483648 to 2147483647。
CharField
字符類型,必須提供max_length參數, max_length表示字符長度。
DateField
日期字段,日期格式 YYYY-MM-DD,相當于Python中的datetime.date()實例。
DateTimeField
日期時間字段,格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ],相當于Python中的datetime.datetime()實例
常用和非常用字段
AutoField(Field)
- int自增列,必須填入參數 primary_key=True
BigAutoField(AutoField)
- bigint自增列,必須填入參數 primary_key=True
注:當model中如果沒有自增列,則自動會創建一個列名為id的列
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)
SmallIntegerField(IntegerField):
- 小整數 -32768 ~ 32767
PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
- 正小整數 0 ~ 32767
IntegerField(Field)
- 整數列(有符號的) -2147483648 ~ 2147483647
PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
- 正整數 0 ~ 2147483647
BigIntegerField(IntegerField):
- 長整型(有符號的) -9223372036854775808 ~ 9223372036854775807
BooleanField(Field)
- 布爾值類型
NullBooleanField(Field):
- 可以為空的布爾值
CharField(Field)
- 字符類型
- 必須提供max_length參數, max_length表示字符長度
TextField(Field)
- 文本類型
EmailField(CharField):
- 字符串類型,Django Admin以及ModelForm中提供驗證機制
IPAddressField(Field)
- 字符串類型,Django Admin以及ModelForm中提供驗證 IPV4 機制
GenericIPAddressField(Field)
- 字符串類型,Django Admin以及ModelForm中提供驗證 Ipv4和Ipv6
- 參數:
protocol,用于指定Ipv4或Ipv6, 'both',"ipv4","ipv6"
unpack_ipv4, 如果指定為True,則輸入::ffff:192.0.2.1時候,可解析為192.0.2.1,開啟此功能,需要protocol="both"
URLField(CharField)
- 字符串類型,Django Admin以及ModelForm中提供驗證 URL
SlugField(CharField)
- 字符串類型,Django Admin以及ModelForm中提供驗證支持 字母、數字、下劃線、連接符(減號)
CommaSeparatedIntegerField(CharField)
- 字符串類型,格式必須為逗號分割的數字
UUIDField(Field)
- 字符串類型,Django Admin以及ModelForm中提供對UUID格式的驗證
FilePathField(Field)
- 字符串,Django Admin以及ModelForm中提供讀取文件夾下文件的功能
- 參數:
path, 文件夾路徑
match=None, 正則匹配
recursive=False, 遞歸下面的文件夾
allow_files=True, 允許文件
allow_folders=False, 允許文件夾
FileField(Field)
- 字符串,路徑保存在數據庫,文件上傳到指定目錄
- 參數:
upload_to = "" 上傳文件的保存路徑
storage = None 存儲組件,默認django.core.files.storage.FileSystemStorage
ImageField(FileField)
- 字符串,路徑保存在數據庫,文件上傳到指定目錄
- 參數:
upload_to = "" 上傳文件的保存路徑
storage = None 存儲組件,默認django.core.files.storage.FileSystemStorage
width_field=None, 上傳圖片的高度保存的數據庫字段名(字符串)
height_field=None 上傳圖片的寬度保存的數據庫字段名(字符串)
DateTimeField(DateField)
- 日期+時間格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
DateField(DateTimeCheckMixin, Field)
- 日期格式 YYYY-MM-DD
TimeField(DateTimeCheckMixin, Field)
- 時間格式 HH:MM[:ss[.uuuuuu]]
DurationField(Field)
- 長整數,時間間隔,數據庫中按照bigint存儲,ORM中獲取的值為datetime.timedelta類型
FloatField(Field)
- 浮點型
DecimalField(Field)
- 10進制小數
- 參數:
max_digits,小數總長度
decimal_places,小數位長度
BinaryField(Field)
- 二進制類型
對應關系:
'AutoField': 'integer AUTO_INCREMENT',
'BigAutoField': 'bigint AUTO_INCREMENT',
'BinaryField': 'longblob',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date',
'DateTimeField': 'datetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'DurationField': 'bigint',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'double precision',
'IntegerField': 'integer',
'BigIntegerField': 'bigint',
'IPAddressField': 'char(15)',
'GenericIPAddressField': 'char(39)',
'NullBooleanField': 'bool',
'OneToOneField': 'integer',
'PositiveIntegerField': 'integer UNSIGNED',
'PositiveSmallIntegerField': 'smallint UNSIGNED',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'longtext',
'TimeField': 'time',
'UUIDField': 'char(32)',
4.2 ORM字段參數
null
用于表示某個字段可以為空。
unique
如果設置為unique=True 則該字段在此表中必須是唯一的 。
db_index
如果db_index=True 則代表著為此字段設置索引。
default
為該字段設置默認值。
DateField和DateTimeField
auto_now_add
配置auto_now_add=True,創建數據記錄的時候會把當前時間添加到數據庫。
auto_now
配置上auto_now=True,每次更新數據記錄的時候會更新該字段。
null 數據庫中字段是否可以為空
db_column 數據庫中字段的列名
db_tablespace
default 數據庫中字段的默認值
primary_key 數據庫中字段是否為主鍵
db_index 數據庫中字段是否可以建立索引
unique 數據庫中字段是否可以建立唯一索引
unique_for_date 數據庫中字段【日期】部分是否可以建立唯一索引
unique_for_month 數據庫中字段【月】部分是否可以建立唯一索引
unique_for_year 數據庫中字段【年】部分是否可以建立唯一索引
verbose_name Admin中顯示的字段名稱
blank Admin中是否允許用戶輸入為空
editable Admin中是否可以編輯
help_text Admin中該字段的提示信息
choices Admin中顯示選擇框的內容,用不變動的數據放在內存中從而避免跨表操作
如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
error_messages 自定義錯誤信息(字典類型),從而定制想要顯示的錯誤信息;
字典?。簄ull, blank, invalid, invalid_choice, unique, and unique_for_date
如:{'null': "不能為空.", 'invalid': '格式錯誤'}
validators 自定義錯誤驗證(列表類型),從而定制想要的驗證規則
from django.core.validators import RegexValidator
from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
如:
test = models.CharField(
max_length=32,
error_messages={
'c1': '優先錯信息1',
'c2': '優先錯信息2',
'c3': '優先錯信息3',
},
validators=[
RegexValidator(regex='root_\d+', message='錯誤了', code='c1'),
RegexValidator(regex='root_112233\d+', message='又錯誤了', code='c2'),
EmailValidator(message='又錯誤了', code='c3'), ]
)
4.3 關系字段
ForeignKey
外鍵類型在ORM中用來表示外鍵關聯關系,一般把ForeignKey字段設置在 '一對多'中'多'的一方。
ForeignKey可以和其他表做關聯關系同時也可以和自身做關聯關系。
to
設置要關聯的表
to_field
設置要關聯的表的字段
related_name
反向操作時,使用的字段名,用于代替原反向查詢時的'表名_set'。
例如:
class Classes(models.Model):
name = models.CharField(max_length=32)
class Student(models.Model):
name = models.CharField(max_length=32)
theclass = models.ForeignKey(to="Classes")
當我們要查詢某個班級關聯的所有學生(反向查詢)時,我們會這么寫:
models.Classes.objects.first().student_set.all()
當我們在 ForeignKey 字段中添加了參數 related_name 后,
class Student(models.Model):
name = models.CharField(max_length=32)
theclass = models.ForeignKey(to="Classes", related_name="students")
當我們要查詢某個班級關聯的所有學生(反向查詢)時,我們會這么寫:
models.Classes.objects.first().students.all()
related_query_name
反向查詢操作時,使用的連接前綴,用于替換表名。
on_delete
當刪除關聯表中的數據時,當前表與其關聯的行的行為。
models.CASCADE
刪除關聯數據,與之關聯也刪除
models.DO_NOTHING
刪除關聯數據,引發錯誤IntegrityError
models.PROTECT
刪除關聯數據,引發錯誤ProtectedError
models.SET_NULL
刪除關聯數據,與之關聯的值設置為null(前提FK字段需要設置為可空)
models.SET_DEFAULT
刪除關聯數據,與之關聯的值設置為默認值(前提FK字段需要設置默認值)
models.SET
刪除關聯數據,
a. 與之關聯的值設置為指定值,設置:models.SET(值)
b. 與之關聯的值設置為可執行對象的返回值,設置:models.SET(可執行對象)
def func():
return 10
class MyModel(models.Model):
user = models.ForeignKey(
to="User",
to_field="id",
on_delete=models.SET(func)
)
db_constraint
是否在數據庫中創建外鍵約束,默認為True。
OneToOneField
一對一字段。
通常一對一字段用來擴展已有字段。
一對一的關聯關系多用在當一張表的不同字段查詢頻次差距過大的情況下,將本可以存儲在一張表的字段拆開放置在兩張表中,然后將兩張表建立一對一的關聯關系。
class Author(models.Model):
name = models.CharField(max_length=32)
info = models.OneToOneField(to='AuthorInfo')
class AuthorInfo(models.Model):
phone = models.CharField(max_length=11)
email = models.EmailField()
to
設置要關聯的表。
to_field
設置要關聯的字段。
on_delete
同ForeignKey字段。
ManyToManyField
用于表示多對多的關聯關系。在數據庫中通過第三張表來建立關聯關系
to
設置要關聯的表
related_name
同ForeignKey字段。
related_query_name
同ForeignKey字段。
symmetrical
僅用于多對多自關聯時,指定內部是否創建反向操作的字段。默認為True。
舉個例子:
class Person(models.Model):
name = models.CharField(max_length=16)
friends = models.ManyToManyField("self")
此時,person對象就沒有person_set屬性。
class Person(models.Model):
name = models.CharField(max_length=16)
friends = models.ManyToManyField("self", symmetrical=False)
此時,person對象現在就可以使用person_set屬性進行反向查詢。
through
在使用ManyToManyField字段時,Django將自動生成一張表來管理多對多的關聯關系。
但我們也可以手動創建第三張表來管理多對多關系,此時就需要通過through來指定第三張表的表名。
through_fields
設置關聯的字段。
db_table
默認創建第三張表時,數據庫中表的名稱。
4.4 多對多關聯關系的三種方式
方式一:自行創建第三張表
class Book(models.Model):
title = models.CharField(max_length=32, verbose_name="書名")
class Author(models.Model):
name = models.CharField(max_length=32, verbose_name="作者姓名")
# 自己創建第三張表,分別通過外鍵關聯書和作者
class Author2Book(models.Model):
author = models.ForeignKey(to="Author")
book = models.ForeignKey(to="Book")
class Meta:
unique_together = ("author", "book")
方式二:通過ManyToManyField自動創建第三張表
class Book(models.Model):
title = models.CharField(max_length=32, verbose_name="書名")
# 通過ORM自帶的ManyToManyField自動創建第三張表
class Author(models.Model):
name = models.CharField(max_length=32, verbose_name="作者姓名")
books = models.ManyToManyField(to="Book", related_name="authors")
方式三:設置ManyTomanyField并指定自行創建的第三張表
class Book(models.Model):
title = models.CharField(max_length=32, verbose_name="書名")
# 自己創建第三張表,并通過ManyToManyField指定關聯
class Author(models.Model):
name = models.CharField(max_length=32, verbose_name="作者姓名")
books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))
# through_fields接受一個2元組('field1','field2'):
# 其中field1是定義ManyToManyField的模型外鍵的名(author),field2是關聯目標模型(book)的外鍵名。
class Author2Book(models.Model):
author = models.ForeignKey(to="Author")
book = models.ForeignKey(to="Book")
class Meta:
unique_together = ("author", "book")
注意:
當我們需要在第三張關系表中存儲額外的字段時,就要使用第三種方式。
但是當我們使用第三種方式創建多對多關聯關系時,就無法使用set、add、remove、clear方法來管理多對多的關系了,需要通過第三張表的model來管理多對多關系。
4.5 元信息
ORM對應的類里面包含另一個Meta類,而Meta類封裝了一些數據庫的信息。主要字段如下:
db_table
ORM在數據庫中的表名默認是 app_類名,可以通過db_table可以重寫表名。
index_together
聯合索引。
unique_together
聯合唯一索引。
ordering
指定默認按什么字段排序。
只有設置了該屬性,我們查詢到的結果才可以被reverse()。
class UserInfo(models.Model):
nid = models.AutoField(primary_key=True)
username = models.CharField(max_length=32)
class Meta:
# 數據庫中生成的表名稱 默認 app名稱 + 下劃線 + 類名
db_table = "table_name"
# 聯合索引
index_together = [
("pub_date", "deadline"),
]
# 聯合唯一索引
unique_together = (("driver", "restaurant"),)
ordering = ('name',)
# admin中顯示的表名稱
verbose_name='哈哈'
# verbose_name加s
verbose_name_plural=verbose_name
4.6 自定義字段(了解)
自定義char類型字段:
class FixedCharField(models.Field):
"""
自定義的char類型的字段類
"""
def __init__(self, max_length, *args, **kwargs):
self.max_length = max_length
super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)
def db_type(self, connection):
"""
限定生成數據庫表的字段類型為char,長度為max_length指定的值
"""
return 'char(%s)' % self.max_length
class Class(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=25)
# 使用自定義的char類型的字段
cname = FixedCharField(max_length=25)
5. choices參數
eg:
性別
學歷
來源
# 針對與這種可以列舉完的可能性,我們就可以使用choices參數
# 在models.py中創建表:
class User(models.Model):
name = models.CharField(max_length=32)
# gender = models.IntegerField()
gender_choices = (
(1, '男'),
(2, '女'),
(3, '其他'),
)
'''
對于choices參數,數據類型該怎么選?
判斷依據是:小元組里面第一個參數的數據類型
'''
gender = models.IntegerField(choices=gender_choices)
"""
####字符串類型的#####
score_choices = (
('A', '優秀'),
('B', '良好'),
('C', '及格'),
('D', '不及格'),
)
score = models.CharField(max_length=8)
"""
# 在tests.py中測試:
import os
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite7.settings")
import django
django.setup()
from app01 import models
# 代碼寫在此處下面
# models.User.objects.create(name='ly', gender=1)
# models.User.objects.create(name='ly2', gender=2)
# models.User.objects.create(name='ly3', gender=3)
# models.User.objects.create(name='ly4', gender=4)
res = models.User.objects.filter(pk=1).first()
print(res.gender) # 1
'''
固定語法結構取值:get_字段名_display()
如果查詢出來的數據不再choices范圍內,會顯示原始數據。
'''
print(res.get_gender_display()) # 男
6. 多對多的創建方式
# 一共三種創建方式
1. 自己創建表關系
2. 通過ManyToManyField自動創建第三張表
3. 設置ManyTomanyField并指定自行創建的第三張表
# 自行創建第三張表
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2)
class Publish(models.Model):
title = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
book = models.ForeignKey(to='Book')
author = models.ForeignKey(to='Author')
create_time = models.DateTimeField()
''''
自行創建第三張表不能使用一下四個方法
add set remove clear
不支持正反向查詢
'''
# 設置ManyTomanyField并指定自行創建的第三張表
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2)
class Author(models.Model):
name = models.CharField(max_length=32)
book = models.ManyToManyField(to='Author', through='Book2Author',through_fields=('author', 'book'))
class Book2Author(models.Model):
book = models.ForeignKey(to='Book')
author = models.ForeignKey(to='Author')
create_time = models.DateTimeField()
7. Ajax技術
# AJAX(Asynchronous Javascript And XML)翻譯成中文就是“異步Javascript和XML”
# 即使用Javascript語言與服務器進行異步交互,傳輸的數據為XML(當然,傳輸的數據不只是XML,現在更多使用json數據)
# 同步交互:客戶端發出一個請求后,需要等待服務器響應結束后,才能發出第二個請求;
# 異步交互:客戶端發出一個請求后,無需等待服務器響應結束,就可以發出第二個請求。
# AJAX除了異步的特點外,還有一個就是:瀏覽器頁面局部刷新;(這一特點給用戶的感受是在不知不覺中完成請求和響應過程)
"""
ajax的精髓:
1. 異步提交
2. 局部刷新
"""
1. 我們不學習原生的ajax(js寫的)
2. 我們目前學習jq封裝之后的
3. 如果想使用ajax,必須引入jquery
# 小案例:
我們在頁面上,來一個簡單計算
# 在settings.py中注釋掉
# 'django.middleware.csrf.CsrfViewMiddleware',
# views.py文件中寫入:
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
# if request.method == 'POST':
if request.is_ajax():
print(request.POST)
d1 = request.POST.get('d1')
d2 = request.POST.get('d2')
d3 = int(d1) + int(d2)
return HttpResponse(d3)
return render(request, 'index.html')
# 在urls.py文件中添加路由:
url(r'^index/', views.index),
# 新建index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="d1"> +
<input type="text" id="d2"> =
<input type="text" id="d3">
<button class="btn btn-success">結果</button>
<script>
$('.btn').click(function () {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
// 直接發起Ajax請求
$.ajax({
// 1.指定提交的請求地址
url:'/index/',
// 2.指定請求方式
type:'post',
// 3.指定提交的數據
data:{d1:d1, d2:d2},
// 4.接收 后端返回的結果
success:function (res) {
// res時后端返回的數據
console.log(res);
$('#d3').val(res)
}
})
})
</script>
</body>
</html>
"""
注意:
----------------------------------------------------------
# views.py文件中寫入:
# 給到前端的時json數據
def index(request):
# if request.method == 'POST':
if request.is_ajax():
print(request.POST)
d1 = request.POST.get('d1')
d2 = request.POST.get('d2')
# d3 = int(d1) + int(d2)
# return HttpResponse(d3)
import json
user_dict = {'name': 'jason', 'hobby': {'like': 'ball'}}
res = json.dumps(user_dict)
return HttpResponse(res)
return render(request, 'index.html')
# 針對前端拿到的json數據取值
# 寫在index.html文件:
// 4.接收 后端返回的結果
success:function (res) {
// res時后端返回的數據
console.log(res);
// 情景一 反序列化
// 后端使用HttpResponse,前端使用下面的方式
res = JSON.parse(res)
console.log(res.name);
{#$('#d3').val(res)#}
}
----------------------------------------------------------
# views.py文件中寫入:
# 給到前端的時json數據
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
# if request.method == 'POST':
if request.is_ajax():
print(request.POST)
d1 = request.POST.get('d1')
d2 = request.POST.get('d2')
# d3 = int(d1) + int(d2)
# return HttpResponse(d3)
# import json
# user_dict = {'name': 'jason', 'hobby': {'like': 'ball'}}
# res = json.dumps(user_dict)
# return HttpResponse(res)
from django.http import JsonResponse
user_dict = {'name': 'jason', 'hobby': {'like': 'ball'}}
return JsonResponse(user_dict)
return render(request, 'index.html')
# 針對前端拿到的json數據取值
# 寫在index.html文件:
// 4.接收 后端返回的結果
success:function (res) {
// res時后端返回的數據
console.log(res);
// 情景一 反序列化
{#res = JSON.parse(res)#}
{#console.log(res.name);#}
// 情景二
console.log(res.name);
{#$('#d3').val(res)#}
}
--------------------------------------------------------------
# views.py文件中寫入:
# 給到前端的時json數據
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
# if request.method == 'POST':
if request.is_ajax():
print(request.POST)
d1 = request.POST.get('d1')
d2 = request.POST.get('d2')
# d3 = int(d1) + int(d2)
# return HttpResponse(d3)
import json
user_dict = {'name': 'jason', 'hobby': {'like': 'ball'}}
res = json.dumps(user_dict)
return HttpResponse(res)
# from django.http import JsonResponse
# user_dict = {'name': 'jason', 'hobby': {'like': 'ball'}}
# return JsonResponse(user_dict)
return render(request, 'index.html')
# 針對前端拿到的json數據取值
# 寫在index.html文件(寫在3 4 之間即可):
// 3.指定提交的數據
data:{d1:d1, d2:d2},
// 情景三 指定請求方式
// 指定后端返回的數據格式
dataType: 'json',
// 4.接收 后端返回的結果
"""