from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
class Electrics(models.Model):
name = models.CharField(max_length=32)
price = models.IntegerField(default=100)
coupons = GenericRelation(to='Coupon') # 用于反向查询,不会生成表字段
def __str__(self):
return self.name
class Foods(models.Model):
name = models.CharField(max_length=32)
price=models.IntegerField(default=100)
coupons = GenericRelation(to='Coupon')
def __str__(self):
return self.name
class Clothes(models.Model):
name = models.CharField(max_length=32)
price = models.IntegerField(default=100)
coupons = GenericRelation(to='Coupon')
def __str__(self):
return self.name
class Coupon(models.Model):
"""
Coupon
id name content_type_id object_id_id
美的满减优惠券 9(电器表electrics) 3
猪蹄买一送一优惠券 10 2
南极被子买200减50优惠券 11 1
"""
name = models.CharField(max_length=32)
content_type = models.ForeignKey(to=ContentType,on_delete=models.CASCADE,null=True,blank=True) # step 1 #关联的那张表
object_id = models.PositiveIntegerField(null=True,blank=True) # step 2 #关联的表中的字段
content_object = GenericForeignKey('content_type', 'object_id') # step 3 方便查询 不会生成表字段
def __str__(self):
return self.name
#python终端打印
from django.contrib.contenttypes.models import ContentType
from app01.models import *
Electrics.objects.filter(id=1).first().coupons.all()
<QuerySet [<Coupon: 小天鹅满减券>, <Coupon: 小天鹅立减券>]>
el = Electrics.objects.filter(id=1).first()
el
<Electrics: 小天鹅洗衣机>
el.model_class()
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'Electrics' object has no attribute 'model_class'
el.__class__
<class 'app01.models.Electrics'>
Coupon.objects.filter(name="小天鹅立减券").first()
<Coupon: 小天鹅立减券>
Coupon.objects.filter(name="小天鹅立减券").first().content_object
<Electrics: 小天鹅洗衣机>
ContentType.objects.filter(app_label="app01",model="electrics").first()
<ContentType: electrics>
ContentType.objects.filter(app_label="app01",model="electrics").first().model_class()
<class 'app01.models.Electrics'>