鉴于这两个模型:
class Item(models.Model):
timestamp = models.DateTimeField()
class Source(models.Model):
items = models.ManyToManyField(Item, related_name="sources")
我可以在给定时间之前找到所有源项目:
source.items.filter(timestamp__lte=some_datetime)
如何有效删除与该查询匹配的所有项目?我想我可以尝试这样的事情:
items_to_remove = list(source.items.filter(timestamp__lte=some_datetime))
source.items.remove(*items_to_remove)
但这看起来很糟糕。
请注意,我不想删除这些项目,因为它们也可能属于其他来源。我只想删除他们与特定来源的关系。
答案 0 :(得分:23)
我认为你在钱上做对了,除了你不需要转换成一个列表。
source.items.remove(*source.items.filter(*args))
remove
/ add
方法如下所示
remove(self, *objs)
add(self, *objs)
并且docs使用以[p1, p2, p3]
的形式添加多个示例,因此我会为remove
投注相同的内容,因为参数是相同的。
>>> a2.publications.add(p1, p2, p3)
进一步挖掘,remove函数逐个迭代*objs
,检查它是否是有效模型,否则使用值作为PK,然后用pk__in
删除项目,所以我要说是,最好的方法是先查询你的m2m表,然后将这些对象传递给m2m管理器。
# django.db.models.related.py
def _remove_items(self, source_field_name, target_field_name, *objs):
# source_col_name: the PK colname in join_table for the source object
# target_col_name: the PK colname in join_table for the target object
# *objs - objects to remove
# If there aren't any objects, there is nothing to do.
if objs:
# Check that all the objects are of the right type
old_ids = set()
for obj in objs:
if isinstance(obj, self.model):
old_ids.add(obj.pk)
else:
old_ids.add(obj)
if self.reverse or source_field_name == self.source_field_name:
# Don't send the signal when we are deleting the
# duplicate data row for symmetrical reverse entries.
signals.m2m_changed.send(sender=rel.through, action="pre_remove",
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=old_ids)
# Remove the specified objects from the join table
db = router.db_for_write(self.through.__class__, instance=self.instance)
self.through._default_manager.using(db).filter(**{
source_field_name: self._pk_val,
'%s__in' % target_field_name: old_ids
}).delete()
if self.reverse or source_field_name == self.source_field_name:
# Don't send the signal when we are deleting the
# duplicate data row for symmetrical reverse entries.
signals.m2m_changed.send(sender=rel.through, action="post_remove",
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=old_ids)
答案 1 :(得分:0)
根据当前的docs,有一个through
属性可让您访问管理多对多关系的表,例如Model.m2mfield.through.objects.all()
那么就您的示例而言:
source.items.through.objects \
.filter(item__timestamp__lte=some_datetime) \
.delete()