帮助删除 Django 中的记录
for u in Users.objects.all():
for g in u.group.all():
if g not in Groups.objects.filter(domain__user=u.id):
u.group.filter(id=g.id).delete()
如何删除关系表中的条目。 在这种情况下,组和用户之间存在多对多关系。 上述代码中的删除语句从 Groups 表中删除该组。 我只想从Users_group表中删除用户和组之间的关系。 我该怎么做呢。
谢谢
for u in Users.objects.all():
for g in u.group.all():
if g not in Groups.objects.filter(domain__user=u.id):
u.group.filter(id=g.id).delete()
How do I delete the entries in relationship table. In this case I have a many to many relationship between Groups and Users. The delete statement in the above code deletes the group from the Groups table.
I just want to delete the relationship between the user and the group from the Users_group table.
How do I do this.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
思考这个问题的关键是要认识到 u.group 是一个管理器,就像 Groups.objects 是一个管理器一样(默认情况下前者是后者的子类)。 您对 u.group 调用的大多数操作都会影响整个 Group 表(有可能首先过滤到与 u 相关的对象)。 这意味着,假设 g 与 u 相关,
则应该与以下情况相同。
在这两种情况下, .filter() 返回一个查询集(相对于 u 来说完全天真)并且 .delete() 删除所有成员。
好消息是 u.group 应该是一个 ManyRelatedManager,这意味着将有其他可用的方法。 有关许多示例,请查看此处。 应该适合您的场景:
The key to thinking about this problem is to realize that u.group is a manager, just as Groups.objects is a manager (by default the former is a subclass of the latter). Most operations that you call on u.group will affect the entire Group table (with the possibility that it first filters down to objects related to u). That means that, assuming g is related to u,
should work the same as
In both cases, .filter() returns a queryset (completely naive with respect to u) and .delete() deletes all members.
The good news is that u.group should be a ManyRelatedManager, meaning that there will be additional methods available for it. For many examples, check here. The one that should fit your scenario: