Home > front end >  In a Django Rest Framework view, does request.user make a database call or the database call happens
In a Django Rest Framework view, does request.user make a database call or the database call happens

Time:09-19

I need to retrieve some information about my users and I am trying to avoid making unnecessary database calls.

The information I need is stored in three models: User, UserProfile and Membership.

Both UserProfile and Membership have a OneToOne relationship with the User model.

I know that I can use select_related() to retrieve related models from the database in a single call. So I could do something like:

User.objects.select_related('userprofile').select_related('membership').get(id=request.user.id)

But that must not be correct, because if I am using some user information to do the query, it means I already retrieved this information in a previous call.

So what would be the best way to get this information minimising database calls? Would it be even possible to get the information from these 3 models in a single call?

CodePudding user response:

DRF performs user related DB query inside authentication class. See source here. So if you need to optimize this query you should implement custom autentication class(see details here), override authenticate_credentials method and use optimized query inside it.

  • Related