Reputation: 65
I have the following models where a Project has many Goals and a Goal has many Tasks.
What is the best way to find a QuerySet containing all Tasks related to an individual Project?
models.py are per below:
class IndividualProject(models.Model):
project = models.CharField(
max_length = 64
)
def __str__(self):
return f"Project {self.project}"
class IndividualGoal(models.Model):
goal = models.CharField(
max_length = 64
)
project = models.ForeignKey(
IndividualProject,
on_delete=models.CASCADE,
related_name="projects",
blank=True,
null=True,
)
def __str__(self):
return f"{self.goal}"
class IndividualTask(models.Model):
task = models.CharField(
max_length = 256,
blank=False,
null=True,
)
goal = models.ForeignKey(
IndividualGoal,
on_delete=models.CASCADE,
related_name="goals",
blank=False,
null=True,
)
I have tried using _set but have had no luck.
I would like to use a query where I select the Project and then select a specific Task.
Upvotes: 0
Views: 104
Reputation: 516
You can start by getting the project from which you'll get all tasks using:-
project = IndividualProject.objects.get(project='name_of_project')
You can then get all tasks related to that project though a goal using:-
tasks = IndividualTask.objects.filter(goal__project=project)
That should give you a Queryset containing all the tasks.
Upvotes: 1