2013-10-29 65 views
0

我有两个模型A和B,其中Django的许多一对多的关系

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

然后我做了以下

a_instance.b_set.clear() 
为了从a_instance删除任何b_instances所有引用

。但后来我得到了以下错误:

Database Error: column a_b/id doesn not exists 
Line 1: SELECT "a_b"."id", 

这是真实的,我中间表A_B在许多一对多的关系(A和B之间)不具有场名为id。它有两个其他字段,而不是a_id和b_id。

那么有谁知道我怎么能强迫Django使用a_id和b_id而不是仅仅是id?

+0

@btoueg,我从文档https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/取得它。他们显示的例子是p2.article_set.clear(),所以它对我来说看起来很合理。 –

+0

确实!我跳到结论... –

回答

0

Django的要求有id字段多对多多种关系表。

0

如果您需要删除两个模型之间的一个实例的关系,可以通过访问关系表的管理器来完成。在M2M关系表可以通过MyModel.relations.through被访问如此删除的关系:

B.As.through.objects.filter(a=a_instance).delete() 

参考:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through

信用:How to remove all relations from manytomany?

+0

我有错误类型对象'A'没有属性'关系' –

+0

'关系'应该是你的关系的名称,比较。编辑。 –

+0

感谢您的澄清,但现在我收到了与我以前完​​全相同的错误 - “a_b表中没有id字段”。任何其他想法为什么会发生? –