原生 Django ContentTypes 实现多态查询优化
不使用第三方库,巧用 ContentTypes + 预加载实现类似模型继承的多态查询。 · 难度:入门 · +10XP
原生 Django ContentTypes 实现多态查询优化
GenericForeignKey 容易导致 N+1 问题。本课教你如何在 Django 自带 ContentTypes 框架上构建高效的多态查询:通过 ContentType 字段 + 外键,加上 select_related 和 prefetch_related 的巧妙组合,实现一次查询获取不同子类对象。同时讲解 Prefetch 对象配合 queryset 过滤,避免全部子类字段暴漏。
# models.py
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Animal(models.Model):
name = models.CharField(max_length=100)
species_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
class Dog(models.Model):
animal = models.OneToOneField(Animal, parent_link=True, on_delete=models.CASCADE)
breed = models.CharField(max_length=100)
# 查询时
animals = Animal.objects.select_related('species_type').prefetch_related(
Prefetch('dog', queryset=Dog.objects.all(), to_attr='dog_instance')
)