简体   繁体   中英

Django getting information from three related tables. Joining tables

I have three tables that are related.

class Book(models.Model):
  year_published = models.IntField()
  author = models.ForeignKey(Author)

class Author(models.Model):
  author_id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=50)
  agent = models.ForeignKey(LitAgent)

class LitAgent(models.Model):
  agent_id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=50)

Ok, I can get a LitAgent like so

getla = LitAgent.objects.get(agent_id=1)

I can get the authors like so

getauthors = Author.objects.filter(agent=getla.agent_id)

But how can I get all the books that an author has too and make sure the books line up to the right author? I also need access to the data in LitAgent and Author too

From my understanding, you want to get the books by using an agent_id. If this is what you want then you can accomplish this using

books = Book.objects.filter(author__agent__agent_id=1)

This will return a list of all books that the author related to the agent with id = 1. If you want to access the author for each book you can use

for book in books:
    print book.author.name
    # in order to print the author agent 
    print book.author.agent.name

On the other side you can reach the books from the LitAgent model.

Lets say

agent = LitAgent.objects.get(agent_id=1)

Then to get the authors it will be

authors = agent.author_set.all()

Now you can iterate

for author in authors:
    for book in author.book_set.all()
         print book

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM