I have a problem with deleting my objects. I wrote a delete method which get a list of IDs of objects to be deleted. This works fine for objects and for objects with foreign keys, but it fails if i have a OneToOneField relationship to the object which i want to delete.
This is my delete method:
@login_required
def delete_objects(request, model, selected_ids):
'''
capsulate a bulk delete method
delete all objects found for the given model
fails silently since model.delete() always fails silently
'''
object_list = model.objects.filter(pk__in=selected_ids)
count = object_list.count()
if count == 1:
name = model._meta.verbose_name.title()
else:
name = model._meta.verbose_name_plural.title()
object_list.delete()
request.user.message_set.create(message='Successfully deleted %s %s' % (count,name))
return
Till now I just tested it with Contact objects. Now I added a PhoneNumber model to my models. The PhoneNumber model has a OneToOneField relationship to the Contact model. If no PhoneNumber object or one PhoneNumber object is assigned to the Contact object i can delete it. But if I relate more than one PhoneNumber object to a Contact object i get an error.
This is the error message that i get:
MultipleObjectsReturned at /crm/contacts/
get() returned more than one PhoneNumber -- it returned 3! Lookup parameters were {'contact__pk': 4L}
Request Method: POST
Request URL: http://127.0.0.1:8000/crm/contacts/
Exception Type: MultipleObjectsReturned
Exception Value:
get() returned more than one PhoneNumber -- it returned 3! Lookup parameters were {'contact__pk': 4L}
I read in the django docs
that "any objects which had foreign keys pointing at the object to be deleted will be deleted along with it." This is the goal I want to accomplish.. but now i get an error. All I want is the objects to be deleted :D
Actually is this maybe a design problem? Is it wrong when I relate more than one PhoneNumber object to a Contact object with a OneToOneField relationship? I have chosen OneToOneField since the phone number is unique and should be related to only one contact.