ContentType
django內(nèi)置的ContentType組件就是幫我們做連表操作
如果一個表與其他表有多個外鍵關(guān)系,我們可以通過ContentType來解決這種關(guān)聯(lián)
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
class DegreeCourse(models.Model):
name = models.CharField(max_length=32)
class Course(models.Model):
name = models.CharField(max_length=32)
# 數(shù)據(jù)庫不生成,只用于鏈表查詢
policy_list = GenericRelation("PricePolicy")
class PricePolicy(models.Model):
period = models.CharField(max_length=32)
price = models.FloatField()
# 課程類型 關(guān)聯(lián)django自動生成的contenttype表
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
# 不在數(shù)據(jù)庫中生成,只用于幫助你做數(shù)據(jù)操作
content_object = GenericForeignKey('content_type', 'object_id')
CORS
即:跨域資源共享(CORS,Cross-Origin Resource Sharing),其本質(zhì)是設置響應頭,使得瀏覽器允許跨域請求
復雜請求在發(fā)送真正的請求前,會先發(fā)送一個OPTIONS請求,第三方服務端先”預檢“一下,”預檢“通過才會發(fā)送正式數(shù)據(jù)。
“預檢”請求時,允許請求方式則需服務器設置響應頭:Access-Control-Request-Method
“預檢”請求時,允許請求頭則需服務器設置響應頭:Access-Control-Request-Headers
“預檢”緩存時間,服務器設置響應頭:Access-Control-Max-Age
帶請求頭的復雜請求
客戶端cors.html
<body>
<h3>CORS示例</h3>
<button type="button" onclick="getData()" >獲取第三方數(shù)據(jù)</button>
<script src="/static/jquery-3.2.1.js"></script>
<script>
function getData() {
$.ajax({
url:'http://127.0.0.1:8000/cors_data/',
type:'GET', // 請求方式:HEAD、GET、POST為簡單請求
headers:{'name':'joe1991'}, //有請求頭的復雜請求
success:function (arg) {
var $tag = $('<h6>');
$tag.text(arg);
$('h3').append($tag);
}
})
}
</script>
</body>
第三方服務端views.py
def cors_data(request):
if request.method == 'OPTIONS':
# 預檢
obj = HttpResponse()
obj['Access-Control-Allow-Origin'] = " http://127.0.0.1:8001"
obj['Access-Control-Allow-Headers'] = 'name' #處理方式不同
# obj['Access-Control-Allow-Methods'] = "PUT"
return obj
else :
obj = HttpResponse('第三方數(shù)據(jù)')
obj['Access-Control-Allow-Origin'] = " http://127.0.0.1:8001"
return obj
區(qū)別
JSONP:主要修改在前端部分,后端需做約束修改,發(fā)jsonp請求
JSONP:只能發(fā)GET請求
CORS:前端的代碼不用修改,服務端的代碼需要修改
CORS:可以發(fā)任意請求,簡單請求與復雜請求處理方式不同