我的Django Manytomany字段都标记为独特,是否有一个选项来删除这个? [英] My Django manytomany fields are all marked unique, is there an option to remove this?
本文介绍了我的Django Manytomany字段都标记为独特,是否有一个选项来删除这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A(models.Model):
def __unicode __(self) :
返回%d%self.id
class B(models.Model):
a_set = models.ManyToManyField(A)
def __unicode __(self):
返回%d%self.id
然后以下一系列操作演示了我的问题:
在[1]中:a1 = A()
在[2] :a1.save()
在[3]中:a1
输出[3]:< A:1>
在[4]中:b1 = B()
在[5]中:b1.save()
在[6]中:b1
输出[6] :< B:1>
在[7]中:b2 = B()
在[8]中:b2.save()
在[9]中:b2
输出[9] :< B:2>
在[10]中:a1.b_set.add(b1)
在[11]中:a1.b_set.all()
输出[11]:[< B :1>]
在[12]中:a1.b_set.add(b2)
在[13]中:a1.b_set.all()
输出[13]:在[14]中:a1.b_set.add(b2)
在[15]中:a1.b_set.all(a)b
()
Out [15]:[< B:1>,< B:2>]
最后我想看到的是:
Out [15]:[< B: 1>,< B:2>,< B:2>]
解决方案
您可以创建第三个表:
类JoinModel(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
我相信这将允许您在A和B的实例之间创建任意数量的关系。
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>]
解决方案
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.
这篇关于我的Django Manytomany字段都标记为独特,是否有一个选项来删除这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文