Django Queryset: filtering by related item manager
<p>I have model for pages that consist of a number of content blocks.</p>

<pre><code>class Page(models.Model):
    ...

class Block(models.Model):
    page = models.ForeignKey(Page)
    ...
</code></pre>

<p>The <code>Block</code> has a handful of other properties that determine whether it is considered to be "active" or not (a couple booleans and a datetime field). I have a manager for the <code>Block</code> model so that I can get a list of active Blocks</p>

<pre><code>Block.objects.active()
Page.objects.first().block_set.active()
</code></pre>

<p>I want to be able to write a queryset to return only <code>Page</code> objects that have active blocks. I would like to do this using the existing <code>Block</code> active manager, so that I am only defining what makes an "active" block once (DRY). IE something like:</p>

<pre><code>Page.objects.annotate(count=Count('block__active')).filter(count__gt=0)
</code></pre>

<p>Obviously that does not work since <code>active</code> is not a property of <code>Block</code>. Is there a way I can use the existing <code>Block</code> manager to achieve this?</p>

<p>Why not just add a boolean field on the model, something like <code>is_active</code>, and update it on <code>save()</code> or <code>set_active()</code>? Then you'll be able to query your Model by that field.</p>

python django django-queryset