title: Django - querying objects via many-to-many relation
body: <p>My models look like this:</p>
  
  <pre><code>class Category(models.Model):
      name = models.CharField(_('name'), max_length=50)
  
  class Product(models.Model):
      name = models.CharField(_('product name'), max_length=40)
      category = models.ManyToManyField(Category)
  </code></pre>
  
  <p>I am trying to build a filter query where I can select 1 or many categories and return products that is connected to all the selected categories.</p>
  
  <p>Example</p>
  
  <p>Product_1 - Belongs to category_1, category_2</p>
  
  <p>Product_2 - Belongs to category_1, category_2 and category_3</p>
  
  <p>When filtering on category_1 and category_2 both products should be returned by the query. When filtering on all 3 categories only Product_2 should be returned since this is the only product related to all selected categories.</p>
  
  <p>The filtering will be dynamic so the number of categories to filter on could be infinite.</p>
  
  <p>How do I do this? I have tried doing </p>
  
  <pre><code>Product.objects.filter(category__in=[1,2,3])
  </code></pre>
  
  <p>But that gives me both product_1 and product_2 since they match ANY of the categories.</p>
  
  <p>I have tried creating a Q filter </p>
  
  <pre><code>Product.objects.filter(Q(category__id=1), Q(category__id=2))
  </code></pre>
  
  <p>But this doesn't return any product.</p>
  
  <p>How would a query like this be constructed to work?</p>