I need help on how to save the same (reference to an) object into a ManyToManyField. For example I have models like this:
class Material(models.Model):
name = models.CharField(max_length=50)
class Compound(models.Model):
materials = models.ManyToManyField(Material)
In this example, the Compound
can be made of one or many different Material
s, and it also could be made from the same Material
twice (same id
in Material
model).
If I try to save through a ModelForm
, the second Material
is discarded because it has the same id
as the first Material
.
What is the best approach for this?
Thank you!
I would suggest doing this as per http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
What am I doing here? Well, Django normally automatically generates an intermediary table for holding pairs of keys associating compounds to elements. In this case we're definiting it ourselves, but not only that, we're adding additional data to the relationship i.e. the quantity you speak of.
As an example usage, what you might do is this:
Don't use a
ManyToManyField
-Create a new model (
MaterialOfCompound
, for example), which holds twoForeignKey
s - one to aMaterial
record and one to aCompound
object.Then, to find all materials a compound is made of, you could use:
or something similar.