0

Given a model:

class Example(models.Model):
    name = models.CharField(max_length=50, blank=True)
    master= models.ForeignKey('Example', on_delete=models.PROTECT, blank=True, null=True)

With this model, it is possible to have an "Example" without any master, or an "Example" can have a master value which is another "Example". Of course, that master "Example" could be foreign-key'ing another "Example". There is no theoretical limit of foreign-key levels.

What is the best way to get all related items for an item, including masters of it's "master"?

For example, if one creates a "child" child=Example(name="Child") and a mother mother=Example(name="mother", master=child), and finally a grandmother, grandmother = Example(name="grandmother", master=mother), the command child.example_set.all() only returns the mother. How to get all related items including the grandmother in this example?

VolkanOzcan
  • 337
  • 1
  • 9
  • 1
    You might want to take a look at `django-mptt`: https://github.com/django-mptt/django-mptt – Willem Van Onsem May 22 '20 at 23:08
  • Another option is `django-treebeard`: https://django-treebeard.readthedocs.io/en/latest/ It uses MP (Materialized Path) trees instead of MPTT. I prefer MP over MPTT because in general it's more efficient and error resistant than MPTT. Django CMS switched from MPTT to Treebeard in version 3.1 because of issues with large trees in MPTT. – MaestroFJP May 23 '20 at 01:16
  • You are right that those methods seem to be better for my use. They also come with additional functionalities one could require during similar tasks. I'll leave the question unanswered for a few more days because we did not answer the question. – VolkanOzcan May 25 '20 at 10:30

1 Answers1

1

Based on your example in your question, you are describing a tree in which you are flattening it in your database. Personally, I'd implement trees using something like MPTT (Modified Preorder Tree Traversa) or MP (Materialized Path) over implementing my own implementation.

There a few great libraries to implement trees in Django -- see django-mptt (MPTT) or django-treebeard (MP). I would suggest looking at the Treebeard tutorial as a first step.

MaestroFJP
  • 366
  • 1
  • 8