您可以使用QuerSet 的prefetch_related 方法来反转select_related。
Asper 文档,
prefetch_related(*查找)
返回一个查询集,它会自动
在单个批次中检索每个指定的相关对象
查找。
这与 select_related 的目的相似,因为两者都是
旨在阻止由以下原因引起的大量数据库查询
访问相关对象,但策略大不相同。
如果您将脱水功能更改为以下功能,则数据库将被单次命中。
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
您不应该在脱水函数中初始化查询集。查询集应始终设置在 Meta 类中。请查看django-tastypie 文档中的以下示例。
class MyResource(ModelResource):
class Meta:
queryset = User.objects.all()
excludes = ['email', 'password', 'is_staff', 'is_superuser']
def dehydrate(self, bundle):
# If they're requesting their own record, add in their email address.
if bundle.request.user.pk == bundle.obj.pk:
# Note that there isn't an ``email`` field on the ``Resource``.
# By this time, it doesn't matter, as the built data will no
# longer be checked against the fields on the ``Resource``.
bundle.data['email'] = bundle.obj.email
return bundle
按照官方django-tastypiedocumentationdehydrate()功能,
脱水
脱水方法采用现在已完全填充的 bundle.data & make
对它的任何最后改动。这对于当一条数据
可能取决于多个领域,如果你想多加一点
不值得拥有自己的领域的数据,或者如果您想要
从要返回的数据中动态删除内容。
dehydrate() 仅用于对 bundle.data 进行任何最后更改。