Search code examples
djangodjango-mptt

Get first descendant with django-mptt


I'm using

try:
    my_group.get_descendants().filter(number=number)[0]
except IndexError:
    pass

when I want to get all groups with my_group as an ancestor but only choose the first. Can I make the database do this for me? I'm thinking of something like

try:
    my_group.get_descendants().filter(number=number).earliest()
except Group.DoesNotExist:
    pass

but am I sure that .earliest() gives me the node 'closest to the ancestor'?


Solution

  • Use the first() method, it does exactly what you want:

    my_group.get_descendants().filter(number=number).first()