title: Django query to compare two foreignkey fields?
body: <p>I have these sample database models </p>
  
  <pre><code>class Book(models.Model):
      name = CharField()
      price = IntegerField()
  
  class Author(models.Model):
      name = CharField()
      book = ForeignKey(Book, related_name='authors')
      type = CharField(choices=('high','medium','low'))
  
  class Random(models.Model):
      book = Foreignkey(Book, related_name='randoms')
      type = CharField(choices=('high','medium','low'))
      rank = PositiveIntegerField()
  </code></pre>
  
  <p>Database Objects:-</p>
  
  <ol>
  <li>b1 = Book('book1', 25)</li>
  <li><p>b2 = Book('book2', 30)</p></li>
  <li><p>Author('author1', b1, 'high')</p></li>
  <li>Author('author2', b1, 'medium')</li>
  <li>Author('author3', b1, 'medium')</li>
  <li><p>Author('author4', b2, 'low')</p></li>
  <li><p>Author('author5', b2, 'low')</p></li>
  <li><p>Author('author6', b2, 'low')</p></li>
  <li><p>Random(b1, 'high', 1)</p></li>
  <li><p>Random(b1, 'medium', 2)</p></li>
  <li>Random(b1, 'low', 5)</li>
  <li>Random(b2, 'low', 3)</li>
  <li>Random(b2, 'high', 0)</li>
  <li>Random(b2, 'medium', 0)</li>
  </ol>
  
  <p>There will be a <code>Random</code> model whose <code>rank</code> represents the correct count of authors of a book of a specific type.
  for eg, If a book has Random(book, 'high', 20). then It means that there have to be 20 authors with type <code>high</code>. if there are more than or less than 20 authors then it's an error.
  I want to filter those <code>Book</code> objects which are having this type of error.</p>
  
  <p>Here <code>b1</code> has zero authors of type = low but it has Random object where rank of 'low' is 5. means there must be 5 authors of type low. <code>b1</code> has error.
  but this is not in case of <code>b2</code></p>
  
  <p>How can I filter those Book objects? </p>