Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango manytomany: adding multiple, non-unique relationships?
    text
    copied!<p>I'm building an app that puts together the hardware of a computer. This is my first time working with django. Say I have the following models:</p> <pre><code>class Memory(models.Model): partNum = models.CharField() capacity = models.CharField() class Computer(models.Model): name = models.CharField() memory = models.ManyToManyField(Memory) # also has cpus, hard drives, and motherboard, but focus on memory for now </code></pre> <p>One memory object can belong to many computer objects, and one computer object can have many memory objects - hense Many-To-Many. However, computers require the same exact memory sticks installed if using more than one. </p> <p>Yet django's manytomany field (by default?) only allows one instance of a memory-computer relationship, it must me unique. Any way around this?</p> <p>If I try, in the admin page, to add many of the same memory objects to a computer, it says "Computer-memory relationship with this Computer and Memory already exists". If I try adding more than once the same memory object to a server object in the manage.py shell, it appears that only one memory object was added. If I try to manually edit the database to have a duplicate entry, I get an error saying that the entry already exists. I see that in the database structure, some sorta "unique together" index thingy is enforcing is enforcing this. If I altered the table to remove that clause, would that solve my problem? Probably not unless the django manager is more stupid than expected.</p> <p>What are my options? Write my own intermediary models and use the <code>through</code> construct? But then I won't get to use the cool filter_horizontal widget! Rewrite my Computer model to have a Foreign Key field plus a field for the number of memory object? But then I won't get the ManyToMany API facilities. Help!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload