在不同列 Django 中预加载 FK 关系

Preload FK relation in different column Django

我有看起来像这样的 Django 模型

class Customer(models.Model):
    name = models.CharField(_("Name"))

class Feature(models.Model):
    label = models.CharField(_("Name"))

class AddOn(models.Model):
    customer = models.ForeignKey(Customer)
    feature = models.ForeignKey(Feature)

假设我有一个 Customer 实例,例如

customer = Customer.objects.get(pk=1)

如何在一次查询中获取特征中的所有标签,以避免 N+1 查询?

目前我所做的是:

[addon.feature.label for addon in self.addon_set.all()]

但我认为如果有很多插件

,每个 addon.feature 都会创建一个不是很优化的查询

您可以使用 values/values_list 在单个查询中获取所有标签

self.addon_set.values_list('feature__label', flat=True)

编辑:ManyToManyField 示例

class Customer(models.Model):
    name = models.CharField(_("Name"))
    features = ManyToManyField('Feature', through='AddOn')

class Feature(models.Model):
    label = models.CharField(_("Name"))

class AddOn(models.Model):
    customer = models.ForeignKey(Customer)
    feature = models.ForeignKey(Feature)

然后您可以执行 customer_obj.features.all()feature_obj.customers.all() 之类的查询,这不会影响您仍然查询 AddOn 模型的能力