美文网首页
django contenttype

django contenttype

作者: nobodyXu | 来源:发表于2018-07-10 17:40 被阅读0次

    from django.shortcuts import render, HttpResponsefrom app01 import modelsfrom django.contrib.contenttypes.models import ContentTypedeftest(request): if request.method == 'GET':

            # ContentType表对象有model_class() 方法,取到对应model        content = ContentType.objects.filter(app_label='app01', model='electrics').first()  # 表名小写        cloth_class = content.model_class() # cloth_class 就相当于models.Electrics        res = cloth_class.objects.all()

            print(res)

            # 为三星电视(id=2)创建一条优惠记录        s_tv = models.Electrics.objects.filter(id=2).first()

            models.Coupon.objects.create(name='电视优惠券', content_object=s_tv)

            # 查询优惠券(id=1)绑定了哪些商品        coupon_obj = models.Coupon.objects.filter(id=1).first()

            prod = coupon_obj.content_object

            print(prod)

            # 查询三星电视(id=2)的所有优惠券        res = s_tv.coupons.all()

            print(res)

            # 查询obj的所有优惠券:如果没有定义反向查询字段,通过如下方式:        content = ContentType.objects.filter(app_label='app01', model='model_name').first()

            res = models.OftenAskedQuestion.objects.filter(content_type=content, object_id=obj.pk).all()

            return HttpResponse('....')

    from django.db import modelsfrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.contenttypes.fields import GenericForeignKeyclassElectrics(models.Model): name = models.CharField(max_length=32)

        coupons = GenericRelation(to='Coupon')  # 用于反向查询,不会生成表字段    def__str__(self):        return self.nameclassFoods(models.Model):    name = models.CharField(max_length=32)

        coupons = GenericRelation(to='Coupon')

        def__str__(self):        return self.nameclassClothes(models.Model):    name = models.CharField(max_length=32)

        coupons = GenericRelation(to='Coupon')

        def__str__(self):        return self.nameclassCoupon(models.Model):    name = models.CharField(max_length=32)

        content_type = models.ForeignKey(to=ContentType) # step 1    object_id = models.PositiveIntegerField() # step 2    content_object = GenericForeignKey('content_type', 'object_id') # step 3    def__str__(self):        return self.name

    相关文章

      网友评论

          本文标题:django contenttype

          本文链接:https://www.haomeiwen.com/subject/dsdqpftx.html