[转载] django contenttypes

https://blog.csdn.net/ayhan_huang/article/details/78626957

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey


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

    def __str__(self):
        return self.name


class Foods(models.Model):
    name = models.CharField(max_length=32)
    coupons = GenericRelation(to='Coupon')

    def __str__(self):
        return self.name


class Clothes(models.Model):
    name = models.CharField(max_length=32)
    coupons = GenericRelation(to='Coupon')

    def __str__(self):
        return self.name

class Coupon(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
from django.shortcuts import render, HttpResponse
from app01 import models
from django.contrib.contenttypes.models import ContentType


def test(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('....')
原文地址:https://www.cnblogs.com/infaaf/p/9582012.html