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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Django之content_type

發布時間:2024/10/12 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django之content_type 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是content type:django內置的一個組件,這個組件幫忙做連表的操作。(混搭連表)

適用場景:適用于一張表與多張表同時做關聯的時候。直接導入就可以使用了。

關聯數據庫說有的表;讓我們可以快速插入數據,并且用反向查找能快速查找到數據。

models.py文件建立表

from django.db import models# Create your models here. from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation from django.contrib.contenttypes.models import ContentTypeclass Course(models.Model):'''普通課程'''title=models.CharField(max_length=32)# 僅用于反向查找price_policy_list=GenericRelation('PricePolicy')class DegreeCourse(models.Model):'''學位課程'''title=models.CharField(max_length=32)# 僅用于反向查找price_policy_list=GenericRelation('PricePolicy')class PricePolicy(models.Model):'''價錢策略'''price = models.IntegerField()period = models.IntegerField()content_type=models.ForeignKey(ContentType,verbose_name='關聯的表名稱')object_id=models.IntegerField(verbose_name='關聯的表中的數據行的ID')content_object=GenericForeignKey('content_type','object_id')# 1. 為學位課“Python全棧”添加一個價格策略:一個月 9.9 """ obj = DegreeCourse.objects.filter(title='Python全棧').first() # obj.id cobj = ContentType.objects.filter(model='course').first() # cobj.id PricePolicy.objects.create(price='9.9',period='30',content_type_id=cobj.id,object_id=obj.id) """

views.py文件,進行數據插入和查看

from django.shortcuts import render,HttpResponse# Create your views here. from app01 import modelsdef test(request):# 1 為學位課python添加一個價格策略:一個月9.9# obj1=models.DegreeCourse.objects.filter(title='python').first()# models.PricePolicy.objects.create(price=9.9,period=30,content_object=obj1)# # obj1 = models.DegreeCourse.objects.filter(title='python').first()# models.PricePolicy.objects.create(price=19.9, period=60, content_object=obj2)# # obj1 = models.DegreeCourse.objects.filter(title='python').first()# models.PricePolicy.objects.create(price=29.9, period=90, content_object=obj3)# # 2 為學位課rest framework添加一個價格策略:一個月9.9# obj1=models.Course.objects.filter(title='rest framework').first()# models.PricePolicy.objects.create(price=9.9,period=30,content_object=obj1)# # obj2 = models.Course.objects.filter(title='rest framework').first()# models.PricePolicy.objects.create(price=19.9, period=60, content_object=obj2)# # obj3 = models.Course.objects.filter(title='rest framework').first()# models.PricePolicy.objects.create(price=29.9, period=90, content_object=obj3)# 3 根據課程的ID獲取課程,并獲取該課程的所有價格策略course=models.Course.objects.filter(id=1).first()price_policys=course.price_policy_list.all()print(price_policys)return HttpResponse('ok')

?

轉載于:https://www.cnblogs.com/zycorn/p/10020490.html

總結

以上是生活随笔為你收集整理的Django之content_type的全部內容,希望文章能夠幫你解決所遇到的問題。

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