Nips
Nips

Reputation: 13870

How to fetch data from model and all of his childrens?

i have models:

class Article(models.Model):
    ...

class Category(models.Model):
    ...
    parent = models.ForeignKey(Category, etc.)
    ...

I would like to retrieve all articles in category, also including child categories to the bitter end.

Ex:

Cat_1
\-Cat_2
  \-Cat_3
    \-Cat_4 (article_1)
  \-Cat3a (article_2)

How to build a query for Cat_1 so as to obtain article_1 and article_2?

Upvotes: 1

Views: 133

Answers (1)

sergzach
sergzach

Reputation: 6754

Idea is:

def retrieve( category = None ):
  if( category )
    _cat = category
  else:
    _cat = Category.objects.get(...)

  if( _cat.parent ):
    return retrieve( _cat.parent )

  return _cat

I hope this can help.

Upvotes: 1

Related Questions