Search code examples
djangopython-3.xdjango-models

error :object can't be deleted because its id attribute is set to None


Trying to Delete an object using shell in django. How do i delete the object say "Ron"?

I use the following command:

t.delete('Ron')

Solution

  • The error:

    object can't be deleted because its id attribute is set to None

    Suggests that you either never saved the object t in the first place, or you changed the primary key (here id) to None manually.

    If you have a single object you can perform a .delete() on the object, for example:

    my_obj = Model.objects.get(name='Ron')
    my_obj.delete()
    

    You should not add extra parameters to delete except for using and keep_parents, as specified in the documentation for Model.delete() [Django-doc]

    Or you can delete the objects with a .filter(…) [Django-doc] statement, like:

    Model.objects.filter(name='Ron').delete()
    

    this will delete all Model objects with name 'Ron'.