Question

Someone on my team wrote a method on our Person Model (an 'extension' of User, although it does not inherit from User):

class Person(models.Model):
    @staticmethod
    def from_user(user):
        try:
            return Person.objects.get(username=user.username)
        except ObjectDoesNotExist:
            return None

So theoretically, Person.from_user(request.user) should return the correct Person. Instead I'm getting AttributeError: 'NoneType' object has no attribute 'objects'.

I'm new to staticmethods, so I might be missing something--but it seems to me that this is impossible. It was easy to solve in other ways; I'm just wondering if there's any real way to have a method of Person return an instance of Person like this, and if I should repair this method or just ditch it.

EDIT: If I jump into PDB and import the model, Person.objects.get(username=user.username) works as expected. Can't see how or where Person is getting set to None.

Was it helpful?

Solution

The code you've shown shouldn't throw an error: it's perfectly valid.

However a better way to do this would be to use a classmethod instead of a staticmethod. The point of a classmethod is that it is automatically passed the class itself, which you can use in the method:

@classmethod
def from_user(cls, user):
    return cls.objects.get(username=user.username)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top