Monday, February 26, 2024

Re: Data model design questio: graph in database

You might consider using GenericRelation. That would allow you to query the edges that have a certain vertex type.

On February 23, 2024 2:20:26 PM CST, "Sébastien Hinderer" <> wrote:
Dear all,

Using the mailing list rather than the forum because, like many visually
impaired people, I find mailing lists way easier to use than forums, I
hope the list is still active.

I need to store in database and manipulate graphs of which both
vertices and edges can each be of several types.

At the moment I am modelling this as follows:

class Vertex(models.Model):

class Vertex_type_1(Vertex):
# Data specific to vertices of type 1

class Vertex_type_2(Vertex):
# Data specific to vertices of type 2

class Edge(models.Model):
src = models.ForeignKey(Vertex,
on_delete=models.CASCADE, related_name="+")
dst = models.ForeignKey(Vertex,
on_delete=models.CASCADE, related_name="+")
class Meta:
unique_together = ['src', 'dst']

class Edge_type_1(Edge):
# Data specific to edges of type 1

class Edge_type_2(Edge):
# Data specific to edges of type 2

I will have to wwite algorithms that work at the graph level, e.g.
to find paths. However, once a path has been found, at some point it
will become necessary to see which types of vertices and edges it is
that are involved in the path that has been found and I am wondering how
I will do that.

More concretely, with the current model, if an edge is found,
does Django have a way to also find out which type of edge it is,
i.e. which child class has given rise to that edge? Or do I need to add
type fields to the Vertex and Edge classes so that it becomes possible
to go from the parent to the children?

I feel unsure because on the one hand it feels to me it is necessary
with the current model to add such type fields, but on the other hand I
feel this is kind of wrong, almost like a code smell suggesting that I
am modelling things in a wrong way.

Any insight would be warmly appreciated as I am a total beginner with

Many thanks in advance,


No comments:

Post a Comment