【问题标题】:Preload FK relation in different column Django在不同的列 Django 中预加载 FK 关系
【发布时间】:2022-01-24 23:06:22
【问题描述】:

我的 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)

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

目前我所做的是:

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

但我认为如果有很多插件,每个addon.feature 都会创建一个不是很优化的查询

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您可以使用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 模型的能力

    【讨论】:

    • 非常有帮助!需要等待5分钟才能接受?
    • @euclid135 您可能会发现使用 AddOn 模型作为“通过”表将 ManyToManyField 从 Customer 添加到 Feature 或反之亦然很有用。它可以简化很多此类查询
    • 我明白了,我不需要添加新的类,而是需要在定义多对多的模型上添加一个字段。我对这个 Django 模型很陌生,直通模型是如何工作的?我还需要从 Addon 模型中查询,因此拥有该模型也很有帮助
    • @euclid135 在答案中添加了一个示例。使用您当前的模型设计,添加 ManyToManyField 只会给您一些帮助/快捷方式
    • 接受并赞成。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多