日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

跨域、ContentType组件

發布時間:2025/7/25 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 跨域、ContentType组件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

先來說一下跨域問題

可以利用script標簽實現跨域:

在demo1中:

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> </head> <body> <button id = "btn">點我給后端發請求</button> </body> <script> $('#btn').click(function () {let script_ele = document.createElement('script');script_ele.src = 'http://127.0.0.1:8000/test?callback=handlerResponse';document.body.insertBefore(script_ele,document.body.firstChild) });function handlerResponse(data) {alert(data)} </script> </html>

在demo2中:

這是利用script標簽進行跨域,這種方式是jsonp,但是jsonp這種方式不能發送post請求,而且比較繁瑣。然后我們利用發送ajax請求跨域。

demo1:

demo2:

這時候訪問時,會報錯,因為不讓我們跨域:

這時候我們寫一個中間件:

要記得把這個中間件在settings中添加進MIDDLEWARE。

這時候就可以訪問了。

?content-type

當我們建的model中,會有很多表,在某一張表中可能會和其他表進行關聯foreignkey,這一張表里會有很多foreignkey,這樣寫就會很麻煩,

這樣寫就會和其他表關聯起來。Django中會有一個content-type表里面存放的是相應app和model的名字。舉個例子:

from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation# Create your models here. class Dianqi(models.Model):name=models.CharField(max_length=32)price=models.IntegerField(default=100)
  # 不會生成字段,只用于反向查詢coupons
=GenericRelation(to="Coupon")def __str__(self):return self.name'''id name1 格力空調2 海爾冰箱'''class Food(models.Model):name = models.CharField(max_length=32)price = models.IntegerField(default=100)class Coupon(models.Model):"""id name dianqi food1 格力空調 1 null"""name = models.CharField(max_length=32)# 第一步 先生成ForeignKey字段 關聯ContentTypecontent_type = models.ForeignKey(to=ContentType)# 第二步 生成一個IntergerField 字段關聯object_id = models.PositiveIntegerField()# 第三步 生成一個GenericForeignKey 把上面兩個字段注冊進去content_object = GenericForeignKey("content_type", "object_id")def __str__(self):return self.name

食物和電器都會有優惠券,

我們查詢的時候怎么查詢呢?

# 生成優惠券# coupon=Coupon.objects.create(name="格力空調滿減券",content_type_id=10,object_id=1)# coupon=Coupon.objects.create(name="格力空調立減券",content_type_id=10,object_id=1)# 查詢# 1 查詢格力空調立減券對應商品的原價格 coupon=Coupon.objects.get(name="格力空調立減券")print(coupon.content_type.model_class())print(coupon.content_type.model_class().objects.filter(pk=coupon.object_id)[0].price)print(coupon.content_object.price)# 2 查詢格力空調所有商品的優惠券 geli=Dianqi.objects.get(name="格力空調")print(geli.coupons.all())

?

轉載于:https://www.cnblogs.com/yb635238477/p/9700552.html

總結

以上是生活随笔為你收集整理的跨域、ContentType组件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。