<p>您可以使用<code>QuerSet</code>的<a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related" rel="noreferrer">prefetch_related</a>方法来反向选择与u相关的。在</p>
<p>Asper文档</p>
<blockquote>
<h3>prefetch_related(*lookups)</h3>
<p>Returns a QuerySet that will automatically
retrieve, in a single batch, related objects for each of the specified
lookups.</p>
<p>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.</p>
</blockquote>
<p>如果您将脱水函数改为following,则数据库将被一次性命中。在</p>
<pre><code>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
</code></pre>
<h2>更新1</h2>
<p>不应在dehydrate函数内初始化queryset。queryset应始终仅在<code>Meta</code>类中设置。请看一下<code>django-tastypie</code>文档中的以下示例。在</p>
^{pr2}$
<p>根据<code>django-tastypie</code><a href="http://django-tastypie.readthedocs.org/en/latest/resources.html#dehydrate" rel="noreferrer">documentation</a>对<code>dehydrate()</code>函数的正式<code>django-tastypie</code><a href="http://django-tastypie.readthedocs.org/en/latest/resources.html#dehydrate" rel="noreferrer">documentation</a></p>
<blockquote>
<p><strong>dehydrate</strong></p>
<p>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.</p>
</blockquote>
<p><code>dehydrate()</code>只用于对bundle.data包. 在</p>