跨域、ContentType组件
生活随笔
收集整理的这篇文章主要介绍了
跨域、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组件的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Nowcoder 提高组练习赛-R3
- 下一篇: 获得 bootstrapTable行号i