将相同的对象两次添加到ManyToManyField [英] adding the same object twice to a ManyToManyField

查看:111
本文介绍了将相同的对象两次添加到ManyToManyField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个django模型类:

I have two django model classes:

class A(models.Model):
     name = models.CharField(max_length = 128)    #irrelevant

class B(models.Model):
     a = models.ManyToManyField(A)
     name = models.CharField(max_length = 128)    #irrelevant

我想做的是以下内容:

a1 = A()
a2 = A()
b = B()

b.a.add(a1)
b.a.add(a1)    #I want to have a1 twice
b.a.add(a2)

assert len(b.a.all()) == 3 #this fails; the length of all() is 2

我猜猜,add()使用一个集合的语义,但是我该怎么规避呢?我试着寻找定制经理,但我不知道这是否正确的方式(似乎很复杂)...

I am guessing that add() uses a set semantic, but how can I circumvent that? I tried looking into custom managers, but I am not sure if this the right way (seems complicated)...

提前感谢

推荐答案

我想你想要的是使用中介模型,使用通过形成M2M关系在ManyToManyField中的关键字参数。类似于上面的第一个答案,但更多的是Django-y。

I think what you want is to use an intermediary model to form the M2M relationship using the through keyword argument in the ManyToManyField. Sort of like the first answer above, but more "Django-y".

class A(models.Model):
    name = models.CharField(max_length=200)

class B(models.Model):
    a = models.ManyToManyField(A, through='C')
    ...

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

当使用通过关键字时,通常的M2M操作方法已不再可用(这意味着添加创建删除或赋值为 = operator)。相反,您必须创建中介模型本身,如下所示:

When using the through keyword, the usual M2M manipulation methods are no longer available (this means add, create, remove, or assignment with = operator). Instead you must create the intermediary model itself, like so:

 >>> C.objects.create(a=a1, b=b)

但是,你仍然可以对包含 ManyToManyField 的模型使用通常的查询操作。换句话说,以下内容仍然可以工作:

However, you will still be able to use the usual querying operations on the model containing the ManyToManyField. In other words the following will still work:

 >>> b.a.filter(a=a1)

但也许更好的例子是这样的:

But maybe a better example is something like this:

>>> B.objects.filter(a__name='Test')

只要中介的FK字段模型不被指定为唯一,您将能够使用相同的FK创建多个实例。您还可以通过添加您喜欢的任何其他字段 C 附加有关关系的附加信息。

As long as the FK fields on the intermediary model are not designated as unique you will be able to create multiple instances with the same FKs. You can also attach additional information about the relationship by adding any other fields you like to C.

中介模型已记录这里

这篇关于将相同的对象两次添加到ManyToManyField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆