42

Quick question. I'm trying yo access one of the fields of a model using a variable.

class ExampleModel(models.Model):
      the_field = models.CharField()
      the_field_two = models.CharField()

How would access the field dynamically? I tried:

model = ExampleModel.objects.get(pk=1)
fieldtoget = 'the_field'
test_var = model[fieldtoget]

But it doesn't seem to work, any ideas how I would do this?

Update: Thought I'd update my question. I'm trying to write a function (as part of larger function) that can not only get the value of the field but also update it from a variable fieldname. For example:

model[fieldtoget] = 'yo'
model.save()

In PHP you can use the {} wrapper - $model{$fieldtoget} - as an example, for dynamic variable names was hoping there was something similar in python :)

Cheers

Ben Kilah
  • 3,445
  • 9
  • 44
  • 56
  • You may also use the _meta attribute of the model. http://stackoverflow.com/questions/3647805/django-get-a-models-fields – Pramod Jul 13 '12 at 13:52
  • 1
    Using the word model for the instance variable of the ExampleModel is probably not a good idea. It is confusing. Perhaps using model_instance might be a better choice. – mtnpaul Dec 06 '12 at 02:56

1 Answers1

85

You can use pythons getattr function to do this. Pass the field name in as the attribute.

getattr(model, fieldtoget)

Since fieldtoget is a variable, this is dynamic.

You can use setattr to set it the same way.

Ashray Baruah
  • 1,585
  • 11
  • 7