A
A
Animkim2016-04-30 17:02:06
Django
Animkim, 2016-04-30 17:02:06

Django how to pull a child?

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True)

Approximately such a model, how can I get descendants?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2016-04-30
@Animkim

category.category_set.all()
If you want prettier:

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')

category.children.all()

U
un1t, 2016-04-30
@un1t

For trees, you can use django-mptt, then you can pull out descendants with any nesting level in one request.

I
iegor, 2016-04-30
@iegor

If you want all descendants, then you need a recursive query. Supported by most SQL, but I doubt that dzhanga can do something like that. It is necessary to write a query in pure sql. As an alternative, you can form a bunch of separate requests in jung, but this is a bad way. Pure sql or maybe someone wrote some library for this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question