开发者

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_n开发者_JAVA技巧ame' 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


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'))


I would create a translation layer between the two namespaces. Since you are using the Django ORM and the JavaScript code is legacy I would assume you would want to do this in Python.

def translate(js_column_name):
    return {
        'firstname': 'first_name',
    }.get(js_column_name, 'string to return when not found')

Using this translation function you could create the keyword arguments in a dictionary and then pass that to the Q function using **:

User.objects.filter(
    Q(**{
        translate(js_firstname) + '_icontains': name
    }) ...

Of course I assume that you would not know the input you are translating is 'firstname' otherwise you could just define the correct column names without needing a function to do it (i.e. just create your query as normal). So instead I assume you are receiving the JavaScript column names dynamically in which case this approach is what I would use.

P.S. I hope this best answers your question. In future I would advise you provide a context for your problem (i.e. specify that you have this problem because..., and that the javascript names appear dynamically etc.). This way your question will get answered more quickly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜