Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering through two foreign key relationships in django

Tags:

django

I have three models:

class Studio(models.Model):
    name = models.CharField("Studio", max_length=30, unique=True)

class Film(models.Model):
    studio = models.ForeignKey(Studio, verbose_name="Studio")
    name = models.CharField("Film Name", max_length=30, unique=True)

class Actor(models.Model):
    film = models.ForeignKey(Film, verbose_name="Film")
    name = models.CharField("Name", max_length=30, unique=True)

I want to query Actor to see if a specific combination of Studio, Film, and Actor exists in the database. I know how to check if Actor exists. I know how to filter for Actor name and Film name. Is there a one-line method to query for Actor name AND Film name AND Studio name (two traversals up the foreign key chain)?

like image 958
Ed. Avatar asked Dec 01 '22 23:12

Ed.


1 Answers

You can do it like this:

Actor.objects.filter(name="actorname",film__name="filmname", film__studio__name="studioname")

Documentation can be found here

like image 160
Aldarund Avatar answered Jan 04 '23 07:01

Aldarund