0

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'?

Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

0

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

my_group.get_descendants().filter(number=number).first()
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • but with `first()` it will result in `None` if the queryset is empty and doesn't it return an entire queryset? Is this the best way to do it? – Jamgreen Mar 06 '15 at 14:27
  • Yes if the queryset is empty then `first()` returns `None`. And yes, this is the best way to do it. – catavaran Mar 06 '15 at 14:32