在 Django 中有效地导入多个嵌套外键关系中的所有对象
To import all objects in multiple nested foreign key relationships efficiently in 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
。
有没有一种有效的方法可以得到所有对应产品的字典对象?
这是我的 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
。