For the following models:
class Entity(models.Model):
name = models.CharField(max_length=256)
class Entry(models.Model):
""" A <subj> has a <connection> to an <obj>
"""
subj = models.ForeignKey(Entity, related_name='subject')
connection = models.CharField(max_length=512)
obj = models.ForeignKey(Entity, related_name='object')
I have this kind of data stored:
A works at Z
B works at Z
B is the brother of C
C lives next door to D
where A, B, C, D and Z are Entity instances
and “works at”, etc are stored in the ‘relation’ field of the Entry model.
Now, how do I proceed to find a link between A and D, considering there are many connections between all of the Entities? I would like to be able to print out something like:
A is connected to D in the 4th degree (and show the steps in the meanwhile).
I’ve tagged this as a Django question as the intent is to use this on a Django-powered website, but I wonder whether Django’s ORM can help here.
Thanks in advance!
This is a graph theory problem. Your model represents edges connecting nodes, and you want to find paths between nodes. There are python libs for this kind of thing, such as the python interface to the Boost library.
read up on graph theory, and check out relevant python packages. The search algorithm you need will be breadth or depth first search.