繁体   English   中英

Django 查询在数据库中没有 N+1 查询的情况下获取外键关联

[英]Django query fetch foreignkey association without N+1 queries in database

我有两个模型, ProductPrice 我使用了 Django 模型的 ForeignKey 关联来定义产品和价格之间的关联。 场景是,一种产品可以根据尺寸有多个价格。 在主页上,我必须获取所有带有价格的产品,并且需要显示它们的价格(可能是底价)。 以下是我尝试过的代码。

class Product(BaseModel):
    name = models.CharField(max_length=50)
    category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL, help_text='Please add new category if not given.')
    image = models.ImageField(upload_to='images/')
    tag = models.ManyToManyField(Tag, help_text='You can add multiple tags')
    slug = models.SlugField(unique=True, null=True)
    time = models.TimeField(verbose_name='Time Required')


class Price(BaseModel):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    size = models.FloatField(validators=[MinValueValidator(0)])
    amount = models.FloatField(validators=[MinValueValidator(0)])

然后在view.py文件中

class ProductListView(ListView):
    model  = Product
    context_object_name = 'products'
    paginate_by = 32

    def get_context_data(self,*args, **kwargs):
        object = super(ProductListView, self).get_context_data(*args, **kwargs)
        object['categories'] = Category.objects.order_by('name')
        return object

    def get_queryset(self):
        return Product.objects.order_by('name')

在模板中,我可以获取并循环浏览类别和产品,但无法访问每个产品的相关价格。 如果我在get_context_data中尝试了一些东西,它会导致 N+1 查询获取每个产品的价格吗?

在模板中,我尝试使用类似{{ product.price_set }}但它返回order.Price.None

使用{{ product.price_set.all }}

为避免过滤器中出现 N+1 个查询,请使用prefetch_related使其看起来像这样。

Product.objects.all().prefetch_related('price_set')

请参阅 Django 文档中的prefetch_related

另请参阅select 相关与预取相关

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM