[Answer]-In Django how can I search for related models based on the order they were added to a ManyToMany Field?

1👍

You should use django-mptt, it provides this feature out of the box.

Your model will be:

class Person(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

Now, you can do the following:

from yourapp.models import Person

dad = Person.objects.create(name="Dad")
john = Person.objects.create(name='John', parent=dad)
jim = Person.objects.create(name='Jim', parent=john)

To solve your lineage problem, once you have your tree in the database, each record (node) will have the following methods:

get_ancestors(ascending=False, include_self=False)
get_children()
get_descendants(include_self=False)
get_descendant_count()
get_next_sibling()
get_previous_sibling()
get_root()
get_siblings(include_self=False)
insert_at(target, position='first-child', save=False)
is_child_node()
is_leaf_node()
is_root_node()
move_to(target, position='first-child')

Leave a comment