django-ContentType的简单使用

本文深入探讨了Django框架中ContentType的使用方法,解释了如何通过ContentType实现多表与同一表的灵活关联,以及如何在视图中操作这些关联。通过具体代码示例,展示了ContentType在实际项目中的应用。

ContentType

  一般我们有多张表同时外键关联同一张表的时候,可以考虑使用ContentType

models.py

 1 from django.db import models
 2 from django.contrib.contenttypes.models import ContentType # django自己生成的表,里面存储着每一个app和它下面的表关系
 3 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 4 
 5 
 6 class PythonBasic(models.Model):
 7     course_name = models.CharField(max_length=32)
 8     coupons = GenericRelation(to='Coupon') ##相当于foreignkey
 9 
10 
11 class Oop(models.Model):
12     course_name = models.CharField(max_length=32)
13     coupons = GenericRelation(to='Coupon') ##相当于foreignkey
14 
15 
16 class Coupon(models.Model):
17     coupon_name = models.CharField(max_length=32)
18     content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) ##
19     object_id = models.PositiveIntegerField() ##
20 
21     content_object = GenericForeignKey("content_type", "object_id") ## 在表中不会真的生成这个字段,但是对应关系是靠它实现的

views.py

 1 class ContentTypeView(View):
 2 
 3     def get(self, request):
 4         # 获取表名
 5         # pb = ContentType.objects.filter(app_label='app01', model='pythonbasic').first()
 6         # print(pb.model_class()) # <class 'app01.models.PythonBasic'>
 7         # print(pb.model_class().objects.all()) # <QuerySet [<PythonBasic: PythonBasic object (1)>, <PythonBasic: PythonBasic object (2)>, <PythonBasic: PythonBasic object (3)>]>
 8 
 9         # obj = PythonBasic.objects.get(id=3)
10         obj = Oop.objects.get(id=2)
11         # Coupon.objects.create(coupon_name="Python基础通关", content_object=obj)
12         print(obj.coupons.all())
13 
14         return HttpResponse('ok')

 

转载于:https://www.cnblogs.com/qq849784670/p/10104962.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值