My Django manytomany fields are all marked unique,

2019-07-22 10:51发布

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>]

2条回答
\"骚年 ilove
2楼-- · 2019-07-22 11:08

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.

查看更多
你好瞎i
3楼-- · 2019-07-22 11:08

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.

查看更多
登录 后发表回答