0

How is the following data structure best represented in a set of Django database models:

Top level element
  An unknown number n of Mid level element(s), n >= 1
    Low level element

For example:

Top
  Mid
    Mid
      Mid
        Bottom

or

Top
  Mid
    Bottom

The issue is that the model for the Mid-level element cannot have both a Mid-level element and a Top-level element as parents. The solutions I can think of are:

Two foreign keys in the Mid-level model

The mid-level model can have a foreign key relationship with Top and another one with 'self'. This seems hacky because if you want to move down through the layers, you have to check both keys at each layer - when you know that only the first Mid has a relationship with Top, while everything else has a relationship with Mid.

class Mid(models.Model):
    top_parent = models.ForeignKey(Top, blank=True, null=True)
    mid_parent = models.ForeignKey('self')

Make Top an instance of Mid instead

Eliminate Top altogether so that Mids always link to other Mids. The issue with this solution is that Top has some unique properties that I don't want to add to Mid if it can be avoided.

Use generic relations

Use generic relations so that Mid can link to both Top and Mid. The downside is that this adds a lot of complexity to the code.

Here's a related question I found a bit later: Django: How do I model a tree of heterogeneous data types?

Jeremy Weirich
  • 387
  • 5
  • 20

1 Answers1

1

The answer could be: make Top a proxy model of Mid.

class Mid(models.Model):
    mid_parent = models.ForeignKey('self')

class Top(Mid):
    # here you have your unique properties
    class Meta:
        proxy = True

As the mid_parent field is required, the Top instance could have itself as mid_parent.

albar
  • 3,020
  • 1
  • 14
  • 27