味觉脱水反相关系数

2024-05-16 06:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的模型,其中包括一个产品和类别表。产品型号具有外键类别。在

当我调用tastypeapi返回categories/API/vi/categories列表时/ 我想添加一个字段来确定“产品数量”/具有给定类别的产品数量。结果是:

category_objects[
{ 
   id: 53
   name: Laptops
   product_count: 7
}, 
...
 ]

以下代码正在工作,但对我的数据库的影响很大

^{pr2}$

有没有更有效的方法来构建这个查询?也许有注解?在


Tags: name模型apiid列表objects产品类别
2条回答

您的代码为每个类别执行额外的计数查询。这是一个很好的问题。在

Django将在GROUP BY语句中包含queryset的所有字段。注意.values()和空的.group_by()将字段设置为必需字段。在

cat_to_prod_count = dict(Product.objects
                                .values('category_id')
                                .order_by()
                                .annotate(product_count=Count('id'))
                                .values_list('category_id', 'product_count'))

上面的dict对象是一个map[category\>;product\u count]。在

可用于dehydrate方法:

^{pr2}$

如果这没用,试着在分类记录上保留类似的计数器,并使用信号来保持它的最新状态。在

注意类别通常是一个树状的存在,你可能还需要计算所有的子类别。在

在这种情况下,请查看包django-mptt。在

您可以使用QuerSetprefetch_related方法来反向选择与u相关的。在

Asper文档

prefetch_related(*lookups)

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

如果您将脱水函数改为following,则数据库将被一次性命中。在

def dehydrate(self, bundle):
    category = Category.objects.prefetch_related("product_set").get(pk=bundle.obj.id)
    bundle.data['product_count'] = category.product_set.count()
    return bundle 

更新1

不应在dehydrate函数内初始化queryset。queryset应始终仅在Meta类中设置。请看一下django-tastypie文档中的以下示例。在

^{pr2}$

根据django-tastypiedocumentationdehydrate()函数的正式django-tastypiedocumentation

dehydrate

The dehydrate method takes a now fully-populated bundle.data & make any last alterations to it. This is useful for when a piece of data might depend on more than one field, if you want to shove in extra data that isn’t worth having its own field or if you want to dynamically remove things from the data to be returned.

dehydrate()只用于对bundle.data包. 在

相关问题 更多 >