django ContentType使用方法
阿新 • • 發佈:2019-01-11
content_type表將app名稱與其中的表的關係進行儲存
models.py
class Test1(models.Model):
name = models.CharField(max_length=100)
#反向查詢
price = GenericRelation('Test3')
class Test2(models.Model):
name = models.CharField(max_length=100)
price = GenericRelation('Test3')
class Test3(models.Model):
price = models.CharField(max_length=100)
contex_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
obj_id = models.IntegerField()
#幫助contentType操作
contex_tobj = GenericForeignKey('contex_type','obj_id')
views.py
obj = Test1.objects.get(id=1) Test3.objects.create(price=10,contex_tobj=obj)