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

最后都变了- 提交于 2019-12-11 01:47:27

问题


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

回答1:


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.




回答2:


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.

  • http://en.wikipedia.org/wiki/Junction_table
  • http://en.wikipedia.org/wiki/Many-to-many_%28data_model%29

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



来源:https://stackoverflow.com/questions/2350855/my-django-manytomany-fields-are-all-marked-unique-is-there-an-option-to-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!