django contenttype

下图即为django的contenttype表

models.py

 1 from django.db import models
 2 from django.contrib.contenttypes.models import ContentType
 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     coupon = GenericRelation("Coupon")   #  反向查询 通过此字段,类似于 releted_name
 9 class Oop(models.Model):
10     course_name = models.CharField(max_length=32)
11     coupon = GenericRelation("Coupon")
12 class Coupon(models.Model):
13     coupon_name = models.CharField(max_length=32)
14     content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # 与django contenttype表建立外键
15 
16     object_id = models.PositiveIntegerField()  # 对应表中的对象id
17 
18     content_object = GenericForeignKey('content_type','object_id') # 不会生成列 

如何查询:

def get(self, request):

    pb = ContentType.objects.filter(app_label="auth",model='user').first() # 与contenttype表字段对应
    pb_model = pb.model_class() # 执行此方法拿到 <class 'django.db.models.base.ModelBase'>
    print(pb_model.objects.all())

如何创建:

object_id = PythonBasic.objects.get(pk=1)
Coupon.objects.create(coupon_name="python优惠卷",content_object = object_id)

 

转载于:https://www.cnblogs.com/lzmdbk/p/10105312.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值