[Django]-Django manytomany: adding multiple, non-unique relationships?

7👍

Edit: sorry, I did not read your post well enough, about not wanting to use ‘through’.

One way to circumvent the problem, would be to use the “through” parameter, in which you can manually specify an intermediate model to use for the many-to-many relationship. In this way, you should still have (most of) the many-to-many facilities that Django provides.

The intermediate model could then have count (which I would find easier to manage than having multiple relations):

class Memory(models.Model):
    partNum = models.CharField()
    capacity = models.CharField()

class Computer(models.Model):
    name = models.CharField()
    memory = models.ManyToManyField(Memory, through='ComputerMemory')

class ComputerMemory(models.Model):
    memory = models.ForeignKey(Memory)
    computer = models.ForeignKey(Computer)
    count = models.IntegerField()

For further information, take a look in the Django documentation: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany

👤nilu

0👍

No this is not a compromise, Even if you dont create another table for the through thing, than also django will create it to remember exactly which memory is associated with each computer, so better is that you do it yourself…and this also allows you to get other fields in there that are required for a specific computer with a specific memory

Leave a comment