rozochkin
rozochkin

Reputation: 709

Clear many to many on multiple objects in Django

Is there any way to bulk clear object relations before delete() method? I've got a model:

class Man(models.Model):
     girlfriends = model.ManyToManyField('Girl')

and want to delete all "Man" objects in views.py:

def delete_all_objects(request):
    men = Man.objects.all()

    #trying to clear objects. getting an error
    men.girlfriends.clear()

    men.delete()
    return HttpResponse("success")

Getting error: 'QuerySet' object has no attribute 'girlfriends'.

Upvotes: 2

Views: 2888

Answers (2)

knbk
knbk

Reputation: 53699

Unless you're also trying to delete all related girls, men.delete() will achieve exactly what you want. The intermediate table has a foreign key to Man, and deleting an object will by default delete all foreign keys pointing to it (unless you override the on_delete behaviour).

Upvotes: 0

hellsgate
hellsgate

Reputation: 6005

The error is correct, the queryset doesn't have a 'girlfriends' attribute. This is because the queryset is a set of Man objects and each of these has the attribute

def delete_all_objects(request):
    men = Man.objects.all()
    for man in men:
        man.girlfriends.clear()
        man.delete()
    return HttpResponse('success')

I haven't tested this but it should be pretty close to what you need.

Upvotes: 4

Related Questions