I am trying to model a directed graph using the Django ORM and have a
working solution (see below), but have the feeling that it could be
improved upon. By "improved" I mean improved efficiency, not going
against the grain of Python/Django etc. I have considered implementing
this outside the Django ORM (using one of the many Python graph
packages), but I also need to be able to run alot of queries against
the properties of both Nodes and Edges so staying with the ORM is by
preferred approach. I have reviewed the previous posts regarding
similar topics (cf.
http://groups.google.com/group/django-users/browse_thread/thread/5e411ab394a6eae5/5b2119706474b7ad?hl=en&lnk=gst&q=model+graph#
http://groups.google.com/group/django-users/browse_thread/thread/624efcfa568046f3/af3d7c5372b6fd6b?hl=en&lnk=gst&q=model+graph#
http://groups.google.com/group/django-users/browse_thread/thread/3511c42235be8cb9/182a73192b3b6815?hl=en&lnk=gst&q=model+graph#)
but they do not seem to provide any hints for improving the solution.
The "requirements" are as follows:

Both Nodes and Edges must be able to accommodate addition of
properties (e.g. a Edge could have a strength property)
The graph may be cyclical.
There may be several Edges between the same two Nodes.
The get_controlling_nodes and get_controlled_nodes will be used a lot
so performance of these is critical (and presently abysmal)

Any feedback greatly appreciated.

from django.db import models

class Node(models.Model):
    title = models.CharField(max_length=255, primary_key=True)

    def get_controlling_nodes(self):
        edges_where_controlled = self.controlled_set.all()
        controllers = []
        for n in edges_where_controlled:
            controllers.append(n.controller)
        return controllers

    def get_controlled_nodes(self):
        edges_where_controller = self.controller_set.all()
        controlled_nodes = []
        for n in edges_where_controller:
            controlled_nodes.append(n.controlled)
        return controlled_nodes

    def __unicode__(self):
        return self.title

class Edge(models.Model):
    controller = models.ForeignKey(Node,
related_name='controller_set')
    controlled = models.ForeignKey(Node, related_name='controlled_set')
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to