Search code examples
djangodjango-modelsdjango-signals

How to access an object's fields and manipulate them when using pre_delete?


I have a foreign key in the model and I want to change a field's value in that object when pre_delete is called. I'm new to this concept and just found out that you use a pre delete signal like this:

@receiver(pre_delete, sender=MyModel)
def bid_deletion(sender, instance, using, **kwargs):
    pass

What should I write to use the foreign key object's field?


Solution

  • You can use the instance, so:

    @receiver(pre_delete, sender=MyModel)
    def bid_deletion(sender, instance, using, **kwargs):
        item = instance.some_foreignkey
        item.field = some_value
        item.save()