title: Sort by a value in a many to one field with a django queryset?
body: <p>I have a data model like this:</p>
  
  <pre><code>class Post(models.Model)
      name = models.CharField(max_length=255)
  
  class Tag(models.Model)
      name = models.CharField(max_length=255)
      rating = models.FloatField(max_length=255)
      parent = models.ForeignKey(Post, related_name="tags")
  </code></pre>
  
  <p>I want to get Posts that have a tag, and order them by the tags rating.</p>
  
  <p>something like:
    Posts.objects.filter(tags__name="exampletag").order_by("tags(name=exampletag)__rating")</p>
  
  <p>Currently, I am thinking it makes sense to do something like</p>
  
  <pre><code>tags = Tags.objects.filter(name="sometagname").order_by("rating")[0:10]
  posts = [t.parent for t in tags]
  </code></pre>
  
  <p>But I like to know if there is a better way, preferably querying Post, and getting me back a queryset.</p>
  
  <hr>
  
  <h2>Edit:</h2>
  
  <p>I don't think this: (<strong>Edit 2 - this <em>does</em> give the correct sorting!</strong>)</p>
  
  <pre><code>Posts.objects.filter(tags__name="exampletag").order_by("tags__rating")
  </code></pre>
  
  <p>will give the correct sorting, as it does not sort only by the related item with name "exampletag"<br>
  Something like the following would be needed</p>
  
  <pre><code>Posts.objects.filter(tags__name="exampletag").order_by("tags(name=exampletag)__rating")
  </code></pre>
  
  <p>I've been looking over the django docs, and it seem "annotate" <em>nearly</em> works - but I don't see a way to use it to select a tag by name.</p>
  
  <hr>
  
  <h2>Edit 2</h2>
  
  <p>Both the Answers are correct! See my comments to observe some epic brain-farts (one test, the results WERE in order, the other i filter and sort by different tags!)</p>
  
  <h3>how it works</h3>
  
  <p>the query</p>
  
  <pre><code>Posts.objects.filter(tags__name="exampletag").order_by("tags__rating")
  </code></pre>
  
  <p>and</p>
  
  <pre><code>Posts.objects.filter(tags__name="exampletag").filter(tags__name="someothertag").order_by("tags__rating")
  </code></pre>
  
  <p>will work correctly and by sorted by the rating of "exampletag"</p>
  
  <p>it seems the tag(From a ForeignKey BackReference Set) used for sorting when calling order_by is the one in the <em>first</em> filter.</p>