Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter across three tables using Django

Tags:

python

django

I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this:


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)

I want to ask for all the literary agents whose authors had books published in 2006, for example. How can I do this in Django? I have looked at the documentation about filters and QuerySets, and don't see an obvious way. Thanks.

like image 969
Vanessa MacDougal Avatar asked Dec 23 '22 05:12

Vanessa MacDougal


1 Answers

LitAgent.objects.filter(author__book__year_published=2006)
like image 125
Ignacio Vazquez-Abrams Avatar answered Jan 02 '23 13:01

Ignacio Vazquez-Abrams