[Answer]-Django how to get specific field with complex join in one-to-many relationship

1๐Ÿ‘

I guess you models look like that:

class Project(models.Model):
    #...


class Section(models.Model):
    #...
    project = models.ForeignKey(Project)


class Task(models.Model):
    #...
    section = models.ForeignKey(Section)

So in order to get a task project you just have to follow the relation.

#when task is a single task object
project = task.section.project

Have in mind that this will make 2 queries (one to get the section and one to get the project) you can optimize this with select_related

tasks = Task.objects.filter(section_id=sectionID).select_related('section__project')
for task in tasks:
    project = task.section.project
    print project.id

ending with a single query.

I guess you can also want to know how to get a queryset of projects contained by some sectionID, in this case you can use the reverse relations like so:

projects = Project.objects.filter(section__id=sectionID)
๐Ÿ‘คTodor

0๐Ÿ‘

You can reach it using task.section.project.id.

๐Ÿ‘คSaeX

Leave a comment