0

I'm trying to learn how I can pass a table variable name through a function. So for example lets say I have a model like below

Bio(models.Model):
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    country = models.CharField(max_length=200)

now I want to be able to pass the table name through the function. So normally I would do a

people = Bio.objects.all()
for x in people:
    print x.name

I want to be able to pass the "name" variable through the function something like this...

def print_name(variable):
    people = Bio.objects.all()
    for x in people:
        print x.variable

print_name(name)

I'm not sure exactly what I should be looking into. Thanks.

NIKHIL RANE
  • 4,012
  • 2
  • 22
  • 45
Ravash Jalil
  • 820
  • 1
  • 9
  • 19

3 Answers3

0

How about this...

print x.__dict__[variable]

now you can pass this variable as string. Hope this helps.

Swakeert Jain
  • 776
  • 5
  • 16
0

You could do

def print_name(variable):
    everyone= Bio.objects.all()
    for x in everyone:
        print x.__getattribute__("name")

print_name("name")
rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

Try following

def print_name(variable):
    people = Bio.objects.all()
    for x in people:
        print getattr(x, variable)

print_name(name)

May be this help.

NIKHIL RANE
  • 4,012
  • 2
  • 22
  • 45