Re: How to reference model instance fields dynamically

2012-10-26 Thread Chris Pagnutti
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: > > Say I have a model like > class MyModel(models.Model) >name =

Re: How to reference model instance fields dynamically

2012-10-26 Thread Brad Pitcher
Use setattr's counterpart, getattr :-) getattr(inst, k).add(relatedObject) On Fri, Oct 26, 2012 at 5:16 PM, Chris Pagnutti wrote: > Awesome. Thanks Brad. Now the question is, what if the attribute is a > ManyToManyField. > > e.g. > inst.k.add(relatedObject) > > How

Re: How to reference model instance fields dynamically

2012-10-26 Thread Chris Pagnutti
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? On Friday, October 26, 2012 11:37:36 AM UTC-4, Chris Pagnutti wrote: > > Say I

Re: How to reference model instance fields dynamically

2012-10-26 Thread Brad Pitcher
You can use python's setattr function to do this: for k,v in fields.iteritems(): setattr(inst, k, v) On Fri, Oct 26, 2012 at 8:37 AM, Chris Pagnutti wrote: > Say I have a model like > class MyModel(models.Model) >name = models.CharField(max_length=100) >

How to reference model instance fields dynamically

2012-10-26 Thread Chris Pagnutti
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