Reputation: 1431
Suppose I have a model named Visitor.
models.py
class Visitor(models.Model):
name = models.CharField(max_length=100,primary_key=True)
region = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
Now what i need to is the following thing
views.py
myView(request):
o = Visitor.objects.get(name='Ankit')
FList = ['region','city','country'] #flist is the list of fields
for myField in FList:
print(o.myField) 'I want to print value of each field for this particular object 'o'.'
I know print(o.myField) is completely incorrect because it will simply try to fetch value of 'myField' field for this particular object from Visitor model and 'myField' field doesn't exist in this model.
How can i achieve this? Thanks in advance.
Upvotes: 0
Views: 26
Reputation: 963
You can use pythons built in function getattr:
for myField in FList:
print(getattr(o, myField))
Upvotes: 3