您可以使用prefetch_related方法QuerSet
来反转 select_related。
Asper 文档,
prefetch_related(*查找)
返回一个 QuerySet,它将在单个批次中自动检索每个指定查找的相关对象。
这与 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-tastypie
文档,dehydrate()
脱水
dehydrate 方法采用现在已完全填充的 bundle.data 并对它进行任何最后的更改。当一条数据可能依赖多个字段时,如果您想插入不值得拥有自己的字段的额外数据,或者如果您想从要返回的数据中动态删除内容,这很有用。
dehydrate()
仅用于对 bundle.data 进行任何最后更改。