views:

21

answers:

1

Hay, i have a model which houses a board

class Board(models.Model):
    parent_board = models.ForeignKey('self', blank=True, null=True)

Each board can belong to another board

So say

Linux
Windows
OS X

can belong to a board called

Computing

These boards house a Thread object

class Thread(models.Model):
    board = models.ForeignKey(Board)

Now, say i assign a Thread to the Windows board, i can get this object easily.

But i want to list all Threads associated with Computing

The Thread belongs to the Windows board, but it will also belong to the Computing board through association.

How can i run a Query on the computing board and retrieve all threads from it's subboards (as well as any belonging to just the Computing thread)?

I've done it, but it's very crude, i wonder if there a more Django way of doing it

Heres my code of it at the moment (working)

listings = [] # blank list to hold clean values
for board in board.board_set.all(): # for each board 
    for listing in board.listing_set.all(): # get the listing from each board
        listings.append( listing ) # append to the listings list
+2  A: 

[Your qn shows a 'Thread' model but then goes on to refer to 'listing_set' in your wokring code - I assume this is a typo?]

You could use Q objects. Assuming that your Board model has a 'name' field containing the board name, I believe the following should work:

from django.db.models import Q
Thread.objects.filter(Q(board__parent_board__name='Computing') | Q(name='Computing'))

The first Q object selects threads which are part of a board which has 'parent_board' set to a board with name 'Computing'. The second Q object selects threads which are directly part of a board which has the name 'Computing'.

msanders
correct, listing is a thread, it got renamed.
dotty
What happens if i dont know the name of the board, and i am getting the board with board = Board.objects.get(pk=4)
dotty
board = Board.objects.get(pk=3) then threads = Threads.objects.filter( Q(board__parent_board=board) ) works a treat!
dotty