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



是否有一种有效的方法来获取与产品对应的所有字典对象

这是我的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'

或者有更好的方法吗?

有没有一种方法可以用更少的查询导入这些数据?

我想你想要的是

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

根据您在每个FK.上定义的related_name,名称可能是错误的

最新更新