Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying an alias to column names in Django

I am currently querying the auth_users table of django to return the users which matched the search criteria.

users = User.objects.filter(
      Q(first_name__icontains = name)| 
      Q(username__icontains = name) | 
      Q(email__icontains = name) | 
      Q(last_name__icontains = name)
   ).values(
      'id', 'username', 'first_name', 'last_name', 'email'
   ).order_by('first_name')

I was wondering if it's possible for me to change the name of 'first_name' to 'firstname'? like we can do in SQL [Select first_name as firstname from auth_users];

so that I can access it by using firstname instead of first_name

Thanks

like image 335
Pranav Garg Avatar asked Nov 16 '10 03:11

Pranav Garg


People also ask

What is __ GTE in Django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value.

Are column alias allowed in FROM clause?

Column Alias Column aliases can be used for derived columns. Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.

What is Django filter?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.

What is a model Django?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .


1 Answers

You can annotate the fields as you want, with the F expression:

from django.db.models import F

users = User.objects.filter(
      Q(first_name__icontains = name) | 
      Q(username__icontains = name) | 
      Q(email__icontains = name) | 
      Q(last_name__icontains = name)
   ).values(
      'id', 'username', 'first_name', 'last_name', 'email'
   ).order_by('first_name'
   ).annotate(firstname = F('first_name'))
like image 100
A K Avatar answered Sep 30 '22 14:09

A K