Django之ContentTypes

ContentTypes是什么?

  • ContentTypes是Django内置的一个应用,可以追踪项目中所有app和model的对应关系,并记录在ContentType表中。

  • 每当我们创建了新的model并执行表数据库迁移后,ContentType表中就会自动新增一条记录。如下表:

什么时候用?

当一张表跟多张表有ForeignKey关系时,可以避免重复写ForeignKey字段,而使用ContentTypes。

表结构

通过使用contenttypes 应用中提供的特殊字段GenericForeignKey,我们可以很好的解决这个问题。只需要以下四步:

  • 在model中定义ForeignKey字段,并关联到ContentType表。通常这个字段命名为“content_type”

  • 在model中定义PositiveIntegerField字段,用来存储关联表中的主键。通常这个字段命名为“object_id”

  • 在model中定义GenericForeignKey字段,传入上述两个字段的名字。

  • 为了更方便查询商品的优惠券,我们还可以在商品类中通过GenericRelation字段定义反向关系。
# 关联模块
from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
# 导入ContentType表
from django.contrib.contenttypes.models import ContentType

class Foods(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField(default=100)
    coupons = GenericRelation(to='Coupon')  # 用于反向查询,关联Coupon

    def __str__(self):
        return self.name

class Coupon(models.Model):
    name = models.CharField(max_length=32)

    content_type = models.ForeignKey(to=ContentType)  #  关联ContentType表
    object_id = models.PositiveIntegerField()  # 存储关联表中的pk
    content_object = GenericForeignKey('content_type', 'object_id')  # 将上面两个字段传入

    def __str__(self):
        return self.name

查询方法

# 正向查询出关联的Foods表
coupon_obj.content_object


# Foods表反向查询Coupon中关联的数据 Foods_obj.coupons.all()

即将秃头的程序员

原文地址:https://www.cnblogs.com/Dream-huang/p/9458558.html