title: In Django, how do I form a queryset that conditionally includes items based on record count in a joined table?
body: <p>We have a media item table, whose items we want to assign varying date ranges.  For example, story X we might like to make available one month, hide it the next month, and make it available again the next month.  So we have a date range table where you can specify multiple start/stop dates.  But if nothing is specified in this table, we want the item to show up.</p>
  
  <p>Question is, how do I write a query where an item is included in results if it has no entries in the date range table, but if it does have one or more entries, it is only included if today's date falls within that range.  Here's what I have so far:</p>
  
  <pre><code>queryset = MediaItem.objects.filter(
      is_active=True, publish_date__lt=timezone.now(),
      mediaitem_date_range__start_date__lt=timezone.now(),
      mediaitem_date_range__stop_date__gt=timezone.now(),
  ).distinct()
  </code></pre>
  
  <p>And the date range model is as follows:</p>
  
  <pre><code>class MediaItemDateRange(models.Model):
      media_item = models.ForeignKey(MediaItem, related_name='mediaitem_date_range')
      start_date = models.DateTimeField(null=True, db_index=True, blank=True)
      stop_date = models.DateTimeField(null=True, db_index=True, blank=True)
  </code></pre>
  
  <p>Currently, this is only yielding results that have entries in the date range table, and most of our items do not have such entries.  I only want to exclude an item if it has an entry there and is not in range of that entry's start/stop dates.</p>
  
  <p>Any thoughts?</p>