title: How to get all objects referenced as ForeignKey from given field in a module in django
body: <p>I have two classes: Author and Book. I want class Authors to have an attribute that contains all books written by the said author, as referenced to as foreign key in the class Books. The method I did does not appear to be working, which I assume is because when the database is being created in migrations, no Books objects exist yet. Or so I believe, I'm pretty new at django.</p>
  
  <pre><code>class Author(models.Model):
      AuthorName = models.CharField(max_length=255, unique=True)
      books = Book.objects.get(pk=object_instance.pk)
  
  class Book(models.Model):
      BookName = models.CharField(max_length=255)
      Author = models.ForeignKey('Author')
  </code></pre>
  
  <p>The error message I get is:</p>
  
  <pre><code>NameError: name 'Book' is not defined
  </code></pre>
  
  <p>Which I get, is because I'm referencing to another class without actually having and instance of that class. I just can't figure out a proper way to do this.</p>
  
  <p>EDIT: I reformatted it to be like this:</p>
  
  <pre><code>class Author(models.Model):
      AuthorName = models.CharField(max_length=255, unique=True)
      books = author.book_set.all()
  
  class Book(models.Model):
      BookName = models.CharField(max_length=255)
      Author = models.ForeignKey('Author')
  </code></pre>
  
  <p>which yields error:</p>
  
  <pre><code>NameError: name 'author' is not defined
  </code></pre>
  
  <p>Maybe I should just query for the datapoints I need later on in views as opposed to creating own field for them in models though..</p>
  
  <p>EDIT 2: solution from answers:</p>
  
  <p>So my mistake all along was to try to add the "books" field in the author table. I guess there's no way to do this then. I can get that method to work in views so I guess this is sort of solved, although not in the way I was originally planning to do it.</p>
  
  <p>doing</p>
  
  <pre><code>class Author(models.Model):
      AuthorName = models.CharField(max_length=255, unique=True)
  
  class Book(models.Model):
      BookName = models.CharField(max_length=255)
      Author = models.ForeignKey('Author')
  </code></pre>
  
  <p>and then later doing this in views:</p>
  
  <pre><code>author = Author.objects.get(pk=1)
  books = author.book_get.all()
  </code></pre>
  
  <p>yields the wanted result (which I sort of knew beforehand, but I was trying to implement a books field in the models, which, if i correctly understood, is not possible at least not with this method).</p>
  
  <p>another solution:</p>
  
  <pre><code>class Author(models.Model):
      AuthorName = models.CharField(max_length=255, unique=True)
  
  class Book(models.Model):
      BookName = models.CharField(max_length=255)
      Author = models.ForeignKey(Author, related_name = "books")
  </code></pre>