wwl
wwl

Reputation: 2065

Filtering nested foreign keys in Django

I'm creating a Scrum board app.

An organization can have multiple Boards, and a Board can have many Tasks.

I'm trying to create a view which contains all tasks of the organization one is in.

To simplify:

models.py of various apps

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)

class Board(models.Model):
    name = models.CharField(max_length=100)
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)

class Organization(models.Model):
    name = models.CharField(max_length=100)


class Task(models.Model):
    name = models.CharField(max_length=100)
    board = models.ForeignKey(Board, on_delete=models.CASCADE)

views.py

def home(request):
    tasks = Task.objects.filter(**NOT SURE HOW TO FILTER**)

    context = {
        'tasks': tasks,
    }
    return render(request, 'tasks/home.html', context)

Currently, in the **NOT SURE HOW TO FILTER** I'm trying board.organization=request.user.profile.organization.

However, I get the error SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

It looks like this is because of board.organization. On the one hand, I need to reference the organization through the Task's board. On the other hand, Django doesn't accept this.

How can I overcome this problem?

Upvotes: 2

Views: 805

Answers (1)

JPG
JPG

Reputation: 88569

Try this,

tasks = Task.objects.filter(board__organization=request.user.profile.organization)

NOTE: You should use @login_required(...) decorator to ensure the user authentication

References

  1. Django ORM making queries
  2. Django orm: Lookups that span relationships

Upvotes: 4

Related Questions