My Django manytomany fields are all marked unique, is there an option to remove this?
Asked Answered
T

2

2

Given a model like this:

class A(models.Model):
    def __unicode__(self):
        return "%d"%self.id

class B(models.Model):
    a_set = models.ManyToManyField(A)

    def __unicode__(self):
        return "%d"%self.id

Then the following series of operations demonstrates my problem:

In [1]: a1=A()
In [2]: a1.save()
In [3]: a1
Out[3]: <A: 1>

In [4]: b1=B()
In [5]: b1.save()
In [6]: b1
Out[6]: <B: 1>

In [7]: b2=B()
In [8]: b2.save()
In [9]: b2
Out[9]: <B: 2>

In [10]: a1.b_set.add(b1)
In [11]: a1.b_set.all()
Out[11]: [<B: 1>]

In [12]: a1.b_set.add(b2)
In [13]: a1.b_set.all()
Out[13]: [<B: 1>, <B: 2>]

In [14]: a1.b_set.add(b2)
In [15]: a1.b_set.all()
Out[15]: [<B: 1>, <B: 2>]

At the end there what I want to see is:

Out[15]: [<B: 1>, <B: 2>, <B: 2>]
Touraco answered 28/2, 2010 at 11:13 Comment(0)
S
2

You can create a third table:

class JoinModel(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)

I believe this will allow you to create any number of relationships between instances of A and B.

Semple answered 28/2, 2010 at 11:30 Comment(1)
ok, that makes sense, but I have a few places where this occurs, so if there is a way of doing it without manually creating the relationship tables then that would be preferableTouraco
E
1

The definition of ManyToMany relationship in relational context is that it represents a function on the subset of the product of the two original spaces. So for each pair of entities there is at most one relation in the M2M associating the pair.

All the main ORM schema generators in fact create a composite PK or UniqueKey over the join table, to force this.

If you want to jump over this, you have to avoid using ManyToMany, and use an explicit table to make the join.

Ezara answered 31/12, 2010 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.