Django cross table model structure

I have a System model, and an Interface model. An Interface is the combination between two systems. Before, this interface was represented as an Excel sheet (cross table). Now I’d like to store it in a database.

I tried creation an Interface model, with two foreign keys to System. This doesn’t work because :

  • It creates two different reverse relationships on the target model
  • It doesn’t avoid having duplicates (first and second rel swapped)

I used this code :

class SystemInterface(Interface):
    assigned_to = models.ManyToManyField(User)
    first_system = models.ForeignKey(System)
    second_system = models.ForeignKey(System)

Isn’t there a better way to do this ?

I’d need to have symmetrical relations : it should’nt matter is a System is the “first” or “second” in an Interface.

Best answer

I think the best simpliest to represent those models would be like this:

class System(models.Model):
    pass

class Interface(models.Model):
    assigned_to = models.ManyToManyField(to=User)
    system = models.ForeignKey(System)

    @property
    def systems(self):
        Interface.objects.get(system=self.system).interfacedsystem_set.all()         

class InterfacedSystem(models.Model):
    interface = models.ForeignKey(Interface)
    system = models.ForeignKey(System)

The add/remove of interfaced system is obviously left as an exercise to the reader, put should be fairly easy.