How to reference model instance fields dynamically

30 views
Skip to first unread message

Chris Pagnutti

unread,
Oct 26, 2012, 11:37:36 AM10/26/12
to django...@googlegroups.com
Say I have a model like
class MyModel(models.Model)
   name = models.CharField(max_length=100)
   number = models.IntegerField()

In a script, I want to have something like
fields = {"name":"Joe", "number":5}

And I want to update a MyModel instance using the fields dictionary, something like this
inst = MyModel.objects.get(pk=2)
for k,v in fields.iteritems():
   inst.k = v   # I tried with inst.F(k) = v and inst.eval(k) = v but python doesn't like that either

I hope I'm being clear in what I'm trying to do.  The reason I have to do it this way is that I don't know which model, and therefore fields, I'm dealing with until run-time.
Please ask questions if this isn't clear.

Brad Pitcher

unread,
Oct 26, 2012, 11:43:10 AM10/26/12
to django...@googlegroups.com
You can use python's setattr function to do this:

for k,v in fields.iteritems():
    setattr(inst, k, v)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/4ZtEPAjlksQJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Chris Pagnutti

unread,
Oct 26, 2012, 8:16:16 PM10/26/12
to django...@googlegroups.com
Awesome.  Thanks Brad.  Now the question is, what if the attribute is a ManyToManyField.

e.g.
inst.k.add(relatedObject)

How to reference k properly if k is a string containing the name of a ManyToManyField of inst?

Brad Pitcher

unread,
Oct 26, 2012, 8:18:06 PM10/26/12
to django...@googlegroups.com
Use setattr's counterpart, getattr :-)

getattr(inst, k).add(relatedObject)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/Rvpb5l-sbaQJ.

Chris Pagnutti

unread,
Oct 26, 2012, 8:29:14 PM10/26/12
to django...@googlegroups.com
Indeed.  Was trying that, but wasn't working on account of me forgetting to save inst first.  It's all good now.  Thanks a mil Brad.  All the best.


On Friday, October 26, 2012 11:37:36 AM UTC-4, Chris Pagnutti wrote:
Reply all
Reply to author
Forward
0 new messages