Intellipaat Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
by (19.9k points)

Im trying to avoid a hardcoding situation in my code

if have a Customer queryset for example the columns are (name,phone,email….)

so if I do

customer = Customer.objects.get(name = 'bbc')

# to get the values of each field I need to do


to avoid having to do this as I need to compare each field in an If statement to make a not of any changes from a form I made a list that contains the column name

Example of the if statement

if == some variable or == some vairiable …..

I made a list that contains the column name to avoid this issue

list = ['name', 'phone' , 'email']

when I do this

for loop 

if customer.list[i] == some variable

I get an error customer doesn't contain attribute list

how can I get around this issue

thanks in advance

1 Answer

0 votes
by (25.1k points)

You can use the getattr function which is built into python. You need to pass the object and attribute name as string to use it. Like this:

if any(getattr(customer, li) == some_variable for li in mylist):

Related questions

0 votes
1 answer
asked Oct 12, 2019 in Web Technology by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories