本文介绍了在Django中有效地删除孤立的m2m对象/标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有两个模型 - 照片和标签 - 通过ManyToManyField连接。

  class Photo(models.Model) :
tags = models.ManyToManyField(Tag)

class标签(models.Model):
lang = models.CharField(max_length = 2)
name_es = models .CharField(max_length = 40)
name_en = models.CharField(max_length = 40)

每隔一段时间,我们会收到孤立的标签,这些标签不再被任何照片引用。有没有一种有效的方法来删除那些标签?我知道这个答案:
/ p>

我们的解决方案现在看起来像这样:

 在Tag.objects.all()中:
如果不是tag.photo_set.select_related():tag.delete()

然而,随着数据库的增加,此脚本的运行时间变得非常高:-P是否有一种从tags表中获取所有标记ID列表的有效方式,然后列出所有标记ID从多对多表创建交集列表?

解决方案

尝试中间表的子查询

  qs = Tag.objects.exclude(pk__in = Book.tags.through.objects.values('tag'))

#然后你可以
qs.delete()

#或者如果您需要触发每个项目的信号
for x in qs:
x。 delete()


I have two models - Photo and Tag - which are connected via a ManyToManyField.

class Photo(models.Model):
    tags = models.ManyToManyField(Tag)

class Tag(models.Model):
    lang = models.CharField(max_length=2)
    name_es = models.CharField(max_length=40)
    name_en = models.CharField(max_length=40)

Every once in a while, we get orphaned tags, that are not referenced any more by any photo. Is there an efficient way of deleting those tags? I know about this answer:Django: delete M2M orphan entries?

And our solution looks like this at the moment:

for tag in Tag.objects.all():
    if not tag.photo_set.select_related(): tag.delete()

However, with increasing database, the runtime of this script is becoming distressingly high :-P Is there an efficient way of getting a list of all tag IDs from the tags table and then a list of all tag IDs from the many-to-many table to create an intersection list?

解决方案

Try sub-query w/ intermediate table

qs = Tag.objects.exclude(pk__in=Book.tags.through.objects.values('tag'))

# then you could
qs.delete()

# or if you need to trigger signal per item
for x in qs:
    x.delete()

这篇关于在Django中有效地删除孤立的m2m对象/标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:01