title: django get latest for each group, group by foreign key
body: <p>Assume I have something like these models:</p>
  
  <pre><code>class Product(models.Model):
    name = models.CharField(max_length=50)
  
  class Sale(models.Model):
    product = models.ForeignKey(Product)
    sale_date = models.DateField()
  </code></pre>
  
  <p>I want to get the latest sale <strong>for each product</strong>. Latest means the latest sale_date. Also, in the same query I want to get the number of products sold for each product.</p>
  
  <p>In SQL terms, I need to group by product_id, to count the number of sales for each product (which is the length of each group). And maybe also to order by date (in each group as well) to get only the latest product sale.</p>
  
  <p>With django ORM I realized I need to somehow use <code>annotate()</code> and maybe in combination with <code>values()</code>. But I still haven't figured how.</p>
  
  <p>Assume I have this <strong>products</strong> table:</p>
  
  <pre><code>| id |   name    |    
  ===================
  | 1  | Book      |  
  | 2  | Telephone |
  </code></pre>
  
  <p>And this <strong>sales</strong> table:</p>
  
  <pre><code>| id | product_id | sale_date |
  =================================
  | 1  |      1     | 05-02-2015 |
  | 2  |      2     | 04-02-2015 |
  | 3  |      2     | 03-02-2015 |
  | 4  |      1     | 06-02-2015 |
  | 5  |      1     | 01-02-2015 |
  </code></pre>
  
  <p>I want to get output like:</p>
  
  <pre><code>| product_id |    name   | sale_date  | num_sales |
  ====================================================
  |     1      | Book      | 06-02-2015 |     3     |
  |     2      | Telephone | 04-02-2015 |     2     |
  </code></pre>
  
  <p>Since 06-02-2015 is the latest sale date for product_id=1 (Book), and 04-02-2015 is the latest date for product_id=2 (Telephone). </p>