Miguel Ike
Miguel Ike

Reputation: 484

How access the all the child of a object related to a model in django?

I'm not sure if my question makes sense, but here is what I'm trying to do:

I have Two Models:

class Task(models.Model):
    title = models.CharField()
    tasklist = models.ForeignKey('TaskList')
class TaskList(models.Model):
    title = models.CharField()
    users = models.ManyToManyField(User, related_name="lists")

How can I get all the tasks for a single User in one line?

Or is the code below the only solution?

user_tasks = []
user_tasklists = request.user.tasklists.all()
for list in user_tasklists:
    for task in list.task_set.all():
        user_tasks.append(task)

Upvotes: 0

Views: 716

Answers (1)

Gocht
Gocht

Reputation: 10256

Assuming you have a user:

user = User.objects.get(pk=some_pk)

# Or if you need get the user from request:
# user = request.user

user_tasks = user.tasklist_set.all()

Now user_tasks is a queryset, so you can filter, or apply any queryset function.

To get Tasks (as shown in your last edit), you need query Task model:

Task.objects.filter(tasklist__users=user)

You can find the related objects documentation here

Upvotes: 2

Related Questions