Galil
Galil

Reputation: 869

Django get user by generic USERNAME_FIELD

Is there a nice way to get a user from Django User model making a query with the generic USERNAME_FIELD instead?

In other words, instead of:

User.objects.get(username='my_user') or User.objects.get(email='[email protected]')

I would like to do something like:

User.objects.get(User.USERNAME_FIELD=a_username_variable)

Obviously, the latter throws a SyntaxError, but I am asking if there is a way to query based on USERNAME_FIELD

Upvotes: 2

Views: 389

Answers (1)

Alasdair
Alasdair

Reputation: 308939

The default ModelBackend authentication backend uses:

user = User._default_manager.get_by_natural_key(username_variable)

This is basically doing:

user = User.objects.get(**{User.USERNAME_FIELD: username_variable})

Upvotes: 1

Related Questions