Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django不使用循环删除多个m2m关系_Django_Django Models_Many To Many - Fatal编程技术网

Django不使用循环删除多个m2m关系

Django不使用循环删除多个m2m关系,django,django-models,many-to-many,Django,Django Models,Many To Many,我试图找到一种最有效的方法,从queryset中的许多对象中删除单个m2m关系。例如,假设我有3个模型类来创建一个消息传递系统——profiles、将多个profile链接在一起的线程,以及链接到单个线程并跟踪哪些profile尚未读取post的post class Profile(models.Model): # stuff here class Thread(models.Model): profiles = models.ManyToManyField('Profile')

我试图找到一种最有效的方法,从queryset中的许多对象中删除单个m2m关系。例如,假设我有3个模型类来创建一个消息传递系统——profiles、将多个profile链接在一起的线程,以及链接到单个线程并跟踪哪些profile尚未读取post的post

class Profile(models.Model):
   # stuff here

class Thread(models.Model):
   profiles = models.ManyToManyField('Profile')

class Post(models.Model):
   thread = models.ForeignKey('Thread')
   not_seen_by = models.ManyToManyField('Profile')
给定一个配置文件:

prof = Profile.objects.get(id=profile_id)
一根线:

thrd = Thread.objects.get(id=thread_id)
和一个包含所有线程帖子的查询集:

msgs = Post.objects.filter(thread=thrd)
msgs
中所有
Post
对象的
not\u seen\u字段中删除配置文件
prof
最有效的方法是什么

最简单的方法是在所有对象之间循环:

for m in msgs:
    m.not_seen_by.remove(prof)
但这似乎不是很有效-
prof
可能在
中,也可能不在
中,不被
看到。能够在queryset本身上调用方法会容易得多,比如
msgs.not\u seen\u by.remove(prof)
。有什么方法可以实现类似的功能吗?如果是这样的话,它会更高效吗?或者它本质上是运行循环的简写代码吗


我已阅读,但使用
Post.not_seen_by.through.objects
仅允许通过
id
Post
profile
进行筛选,因此,我无法将
remove
操作仅限于那些链接到thread
thrd
帖子。我建议明确中间模型,然后直接使用其管理器:

class Profile(models.Model): 
    # stuff here

class Thread(models.Model): 
    profiles = models.ManyToManyField('Profile') 

class Post(models.Model): 
    thread = models.ForeignKey('Thread') 
    not_seen_by = models.ManyToManyField('Profile', through='NotSeenBy')

class NotSeenBy(models.Model):
    post = models.ForeignKey('Post')
    profile = models.ForeignKey('Profile')

prof = Profile.objects.get(id=profile_id)
thrd = Thread.objects.get(id=thread_id)
NotSeenBy.objects.filter(post__thread=thrd, profile=prof).delete()

在我的视图中,您可以将删除限制为特定线程的帖子

像这样

Post.not_seen_by.through.objects.filter(post__thread=t, profile=prof).delete()
如果我错了,请告诉我

如果这不起作用,您可以始终使用Django中的
.Raw
编写原始查询。然后使用SQL的魔力来实现这一点。:);)