1

I have an interesting question. I have class model:

class Patient(models.Model):
    separation = models.ForeignKey(Separation, blank=True,
                                   null=True, default=None)
    number_card = models.IntegerField(default=0)

I can write:

patient = Patient()
patient.name = 'Saney'

But what should I do if I don't know what property I must changed. For example, the name of property what must changed come in the variable " property='name' ". But if I write next code:

patient.property = 'Saney'

python doesn't understand that I mean that I want write 'Saney' into patient.name and not to patient.property. And when I try to testing some thing, for example:

 patient.'name'= 'Saney'

python of course gave an error...)

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555

1 Answers1

1

You can use setattr(..) for that:

setattr(patient,'name','Saney')

which is equivalent to:

patient.name = 'Saney'

The setattr(..) builtin has the following structure:

setattr(object, name, value)

   This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555