Hi.

So I came across a use-case for wanting to delete content (which
django doesn't really handle exactly to my liking).  I just got back
from a vacation in vegas and noticed in a drunken stupor I had posted
some pictures on my blog that should I really shouldn't have (
http://i.imgur.com/5oj15.jpg SFW).

Anyhow, currently django's only delete behavior (to my knowledge) is
to delete all objects related from a reverse relation.  I think it
would be preferable to actually delete only objects that have NOT NULL
**and** no default set.

Right now clear() sort of fills some of the void for what you need to
do prior to deleting an object, but it fails to handle DEFAULT
conditions.

I realize changing the default behavior of the delete() method is
probably out of the question... and there are a bunch of tickets open
asking for cascades and what-not, that will hopefully one day fill the
void.  clear(), however, *should* handle DEFAULTS in the same way it
handles null=True.

Also, I wrote a mix-in class that fixes the delete method to work as I
believe it should... for those of you with similar use-cases.  Anyone
have any feedback on it?

ps.  I didn't really murder a hooker in vegas (I don't even have a
blog), just felt that I should provide a relevant use-case ;)

from django.db.models.fields import NOT_PROVIDED
from django.contrib import admin

class ClearOnDelete(models.Model):
    def delete(self):
        related_objects = self._meta.get_all_related_objects()
        for object in related_objects:
            accessor_name = object.get_accessor_name()
            related_accessor = getattr(self.__class__, accessor_name)
            related_accessor_instance = getattr(self, accessor_name)

            if related_accessor.related.field.default is not
NOT_PROVIDED:
                for relation in related_accessor_instance.all():
                    setattr(relation,
related_accessor.related.field.name,
related_accessor.related.field.default)
                    relation.save()
            elif related_accessor.related.field.null:
                for relation in related_accessor_instance.all():
                    setattr(relation,
related_accessor.related.field.name, None)
                    relation.save()
        super(ClearOnDelete, self).delete()

    class Meta:
        abstract = True

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-develop...@googlegroups.com.
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to