您可以使用prefetch_related方法QuerSet
來反轉select_related。
阿斯皮爾文檔,
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-tastypie
documentation上dehydrate()
功能,
脫水
的脫水方法採用現在完全填充bundle.data &使 任何最後改變它。當一段數據 可能依賴於多個字段時,如果您要推入額外的 不值得擁有自己的字段的數據,或者如果您想要動態地將數據從數據中移除回。
dehydrate()
僅用於對bundle.data進行最後的修改。
設置緩存? – forivall