Home > Enterprise >  How to use objects.filter for (one-to-many) releation
How to use objects.filter for (one-to-many) releation

Time:12-11

I have 3 tables: Job, Flight, and Image One job can have multiple flights and a flight can have only one job. And a flight can have many images. I get all flights related to the job using the query:

flights = Flight.objects.filter(job_id=job_id)

and now I want all images in those flights to call a function for all images but I couldn't implement it without a loop:

for flight in flights:
        images = Image.objects.filter(flight=flight)
        data = process_images(images)

I want something like:

images = Image.objects.filter(flight=flights)

so I call process_images only once, is that possible?

CodePudding user response:

You can use __ to follow a Foreign Key relationship.

images = Image.objects.filter(flight__job_id=job_id)
  • Related