pythondjangodjango-models

Query Django Users by get_username method


I am trying to get the Django User object with a specific username. The obvious way to do it is like this:

from django.contrib.auth.models import User
bob = User.objects.get(username="Bob")

But I noticed that User objects have a get_username() method which states that

you should use this method instead of referencing the username attribute directly.

This makes me wary of using the attribute in queries.

Is there a way to query User objects by this method instead of by the username attribute? I'm looking for a more elegant, queryset-oriented version of this:

bob = [u for u in User.objects.all() if u.get_username() == "Bob"][0]

if such a thing exists.


Solution

  • This makes me wary of using the attribute in queries.

    You are not really using attributes in a query. You are only using attributes from the class that are subclasses of django.db.models.fields.Field. So you can not filter with an arbitrary attribute, or method.

    Luckily, if we look at the source code of .get_username(…) [GitHub], it says:

    def get_username(self):
        """Return the username for this User."""
        return getattr(self, self.USERNAME_FIELD)
    

    this is used for example if you want to use the email field instead of username, or when make a custom user model with another field.

    We can then make the query with:

    from django.contrib.auth.models import User
    
    bob = User.objects.get(**{User.USERNAME_FIELD: 'Bob'})