在 django 中有效导入多个嵌套外键关系中的所有对象

时间:2021-07-21 10:08:20

标签: django orm

有没有有效的方法获取对应的所有字典对象到产品?

这是我的 django 模型

class Product(models.Model):
    ...

class Ingredient(models.Model):
    product = FK(Product)
    middle = FK(Middle)
    ...

class Middle(models.Model):
    dictionary = FK(Dictionary)
    ...

class Dictionary(models.Model):
    ...

我这样做的方式。

product = Product.objects.get(id=1)
ingredients = ProductIngredient.objects.filter(product=product)
middles = ProductMiddle.objects.filter(ingredient__in=ingredients)
dictionaries = ProductDictionary.objects.filter(middle__in=middles)

但是我想要

dictionaries = product.ingredient.middle.dictionary.all() (?)
# AttributeError: 'RelatedManager' object has no attribute 'middle'

或者 有没有更好的办法?

有没有办法用更少的查询来导入这些数据?

1 个答案:

答案 0 :(得分:0)

我认为你想要的是

dictionaries = Dictionary.objects.filter(middle__ingredient__product_id=1)

名称可能有误,具体取决于您在每个 FK 上定义的 related_name

相关问题