博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django之ContentTypes
阅读量:7059 次
发布时间:2019-06-28

本文共 1354 字,大约阅读时间需要 4 分钟。

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 ContentTypeclass Foods(models.Model):    name = models.CharField(max_length=32)    price = models.IntegerField(default=100)    coupons = GenericRelation(to='Coupon')  # 用于反向查询,关联Coupon    def __str__(self):        return self.nameclass 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

你可能感兴趣的文章