Django不使用循环删除多个m2m关系
我试图找到一种最有效的方法,从queryset中的许多对象中删除单个m2m关系。例如,假设我有3个模型类来创建一个消息传递系统——profiles、将多个profile链接在一起的线程,以及链接到单个线程并跟踪哪些profile尚未读取post的postDjango不使用循环删除多个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')
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
操作仅限于那些链接到threadthrd
的帖子。我建议明确中间模型,然后直接使用其管理器:
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的魔力来实现这一点。:);)