title: DJANGO: Sorting sets of sets
body: <p>I have this models (simplified): </p>
  
  <pre><code>#models.py
  
  class Expression(models.Model):
      text = models.CharField(max_length=254)
  
  class Country(models.Model):
      name = models.CharField(max_length=100)
  
  class Definition(models.Model):
      expression = models.ForeignKey(Expression)
      country = models.ForeignKey(Country)
      text = models.CharField(max_length=254)
  
  class Vote(models.Model):
      definition = models.ForeignKey(Definition)
  </code></pre>
  
  <p>And this view</p>
  
  <pre><code>#views.py
  
  def index(request):
      expressions = Expression.objects.all()
      return render(request, 'expression_index.html', { 'expressions':expressions)
  </code></pre>
  
  <p>So it will show the last 10 created expressions.</p>
  
  <p>Then in the template I have this:</p>
  
  <pre><code>#index.html
  
  {% for expression in expressions %}
      {{ expression }}
      {% for definition in expression.definition_set.all %}
          &lt;ul&gt;
              &lt;li&gt;{{ definition }}&lt;/li&gt;
          &lt;/ul&gt;
      {% endfor %}
  {% endfor %}
  </code></pre>
  
  <p>Every definition has several votes.
  Every vote is a single row so we can do:</p>
  
  <pre><code>definition.votes_set.count()
  </code></pre>
  
  <p>How can I achieve to display them like this:</p>
  
  <p>The top definition of every country alphabetically. Each country appears only with one definition.</p>
  
  <p>Lets say Germany has two definitions for expression "A" and Denmark has three definitions for the same expression it will show only two definitions: the one with the most votes.</p>
  
  <p>I hope I'm making sense.</p>
  
  <p>Thanks</p>