Search code examples
python-3.xdjangodjango-modelstyping

Is there a Pythonic way to type a function parameter to a specific django model object?


Let's say I have a model like this:

class Foo():
   name = models.CharField()

And a function like this:

def update_foo_name(foo_object):
   foo_object.name = "New Name"

Is there a way to enforce typing on update_foo_name(), so that only a valid object of Foo can be passed here?

Ie something like update_foo_name(foo_object: Foo.objects).

Apologies if this has already been asked, and thank you in advance for any responses!


Solution

  • a pythonic way should be

    class Foo():
        name = models.CharField()
        
        def change_name(self, new_name: str):
            self.name = new_name
            self.save()
    

    if you really wanna do it out of Foo scope, in a global function or from a Bar class for example, a way to guarantee is:

    class Bar()
       ...
    
        def method_to_change_foo_name_for_any_reason(self, foo: Foo):
            assert isinstance(foo, Foo), TypeError("Not a Foo object")
            foo.name = "New name that bar gives to foo"
            foo.save()