[Answer]-Django Many-To-One on delete

1πŸ‘

βœ…

I think you are trying to control message deletion in wrong place.

Current logical chain:

py: user.delete() 
    -> db: delete .. from tuser
        -> db: cascade .. 
            -> db: trigger ..
                -> py: ??? // trying to somehow catch last message 

In such way business logic is mostly placed in db and not in orm, and there are problem on how to link db events with py callbacks. Or may be not to link them at all and place all logic into db?

If you want to manage deletion with orm, the logic should look like this:

py: user.delete():
    py: messages = user.select_all_messages() // get all messages
    py: for msg in messages: msg.delete() // or do what you want to do
        -> sql: delete .. from tmessage
    py: user.really_delete_from_db()
        -> db: delete .. from tuser
            x db: cascade .. // already done
                x db: trigger .. // no need to catch events

In this way you firstly delete all dependent objects with full control on their deletion, and only then delete user entries without any unmanageable side-effects

πŸ‘€akaRem

0πŸ‘

Why do you delete the user ? You just could add a Boolean field to deactivate it. So you won’t have to handle your messages issues.

class User(models.Model)
    is_activated = models.BooleanField(default=True)

class Message(models.Model)
    #there are some fields
    #...
    user = models.ForeignKey('User')
πŸ‘€pepourquier

Leave a comment