On Mon, Jun 24, 2013 at 5:43 AM, Victor Rajewski <askvic...@gmail.com>wrote:

> I have a custom minimal user model subclassing AbstractBaseUser,
> containing little more than an email address, for use with
> django-social-auth. However, I'm using an externally-developed app which
> queries the user model using the username field, which in my case does not
> exist, resulting in a FieldError. Rather than modifying the external app,
> it would be nicer to handle this within the User model. While the
> AbstractBaseUser model does call for specifying which field is the username
> with the USERNAME_FIELD property, it doesn't actual allow referencing that
> field as 'username' in a query.
>

It actually does - you just need to be a little clever about it.

There are two ways -- the hard way (using raw queries), and the easy way.

The hard way:

user = UserModel.objects.get(**{UserModel.USERNAME_FIELD: desired_username})

This exploits the fact that you can pass kwargs to any function, and that
Django's query language is really just a syntax associated with kwarg keys.
You create a dictionary that describes the query you want, and you unroll
it in your User queries.

This is a common enough pattern that it's wrapped up in an easier way:

UserModel.objects.get_by_natural_key(desired_username)

This uses the serialisation infrastructure to do exactly the same query
(you can check the source code if you want :-)

Yours,
Russ Magee %-)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to