Efficiently delete orphaned m2m objects/tags in Django

前端 未结 3 1526
遇见更好的自我
遇见更好的自我 2021-01-05 17:06

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

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

class Tag(m         


        
3条回答
  •  情话喂你
    2021-01-05 18:12

    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()
    

提交回复
热议问题