I am using Django 3.2 and I am having to monkey patch a model, based on some conditional logic.
myapp/models.py
class Foo(models.Model):
# fields ...
# methods ...
pass
in console
from myapp.models import Foo
def something(obj):
return obj.id
# Monkey patching the class (model)
setattr(Foo, 'mysomething', something)
# Fetch an instance form db
f = Foo.objects.all().first()
f.mysomething()
# return 1 (correct)
My surprise is the fact that the something method is not accepting an argument, and instead, seems to be using the argument specified in the definition (obj) as a synonym for self - and therefore, the method is acting like an instance method.
Can anyone explain the technical reason why this is happening - and is this documented (and therefore consistent) behaviour I can rely on in my code?