Home > OS >  Django-python coding explanation
Django-python coding explanation

Time:02-17

What is static method and how can we explain the below code ?

  @staticmethod
    def get_model(**kwargs):
        try:
            return Model.objects.get(**kwargs)
        except Model.DoesNotExist:
            return

CodePudding user response:

In short and maybe oversimplified: staticmethod doesn't require object of a class to run. This also means that you don't need self argument.

About the code: This method is attempting to return single (.get()) instance of a Model that match with parameters specified in kwargs.

example:

kwargs = {"id":5, "is_alive": True}

Model.objects.get(**kwargs)

#is the same as

Model.objects.get(id=5, is_alive=True)

This can raise Model.DoesNotExists error if there is no instances of Model matching with paramaters so try/except is used.

If Model.DoesNotExists error is raised then method return None.

CodePudding user response:

A staticmethod is a function not bound to an object, but is encapsulated within it ( typically to reduce outer namespace clutter, or eliminate any need to import it). It doesn't have the first self argument that a normal object method does.

  • Related