user2800761
user2800761

Reputation: 2335

How to identify a column name by a string? django/python

I am writing a basic function that takes three arguments, request, field, and user_id. The idea is, when you pass through the info, the function returns the result which would be the column (identified by argument "field"), the row (identified by the argument "user_id"). this is my function:

def get_user_field(request, user_id, field):
    result = Users.objects.raw("SELECT id, %s FROM blog_users WHERE id = %s", [field, user_id])[0]
    #return result.??????

what I do not know how to do is to replace those question marks with what to return the corresponding column. If i try

return result.field

It will pass a string where "field" is. And of course a string cannot be put there.

So how can i achieve a function that works pretty much exactly like this and returns one result?

Thanks!

Upvotes: 2

Views: 249

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

This can be done with the getattr Python builtin:

return getattr(result, field)

But it would be better to do it entirely differently:

def get_user_field(request, user_id, field):
    return User.objects.filter(id=user_id).values_list(field, flat=True)[0]

Or, to allow for the possibility of the user not existing:

def get_user_field(request, user_id, field):
    result = User.objects.filter(id=user_id).values_list(field, flat=True)
    if result:
        return result[0]
    else:
        return None # or raise an exception or whatever you like

Upvotes: 4

Related Questions