Ah, it works for me too, except in the case of relations. Essentially, it all comes down to one line of code; given an instance model, a method as a string, and a secondary instance of a model, something like:
getattr(model_instance, attr_name).add(model_to_add) So, something like: >>> from project.models import MyModel >>> my_model = MyModel(attr1 = 'value') >>> my_model.attr1 # works fine, of course 'value' >>> getattr(my_model, 'attr1') # also works, no surprises yet 'value' >>> getattr(my_model, 'some_relation_or_fk') # but... Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Python/2.5/site-packages/django/db/models/fields/ related.py", line 235, in __get__ raise self.field.rel.to.DoesNotExist DoesNotExist So I can't assign it to a variable (in order to set it)... Any ideas? -Alex. On Oct 6, 7:38 pm, "Russell Keith-Magee" <[EMAIL PROTECTED]> wrote: > On Tue, Oct 7, 2008 at 5:53 AM, Alex G <[EMAIL PROTECTED]> wrote: > > > Dear django-users, > > > Does anyone know of a way to dynamically create an object related to a > > model whose name is not known until runtime? Essentially, I have a > > situation wherein I need to create this associated object, but seem to > > have no way of getting at it. > > > I am trying to do it by way of getattr(self, attr_name), but it would > > seem that the nature of relationships dictates that the attribute > > designated by attr_name is in fact a method masquerading as an > > attribute by way of property, so any attempt to retrieve it runs the > > method, which causes: > > > Traceback (most recent call last): > > File "<stdin>", line 1, in <module> > > File "/Library/Python/2.5/site-packages/django/db/models/fields/ > > related.py", line 235, in __get__ > > raise self.field.rel.to.DoesNotExist > > django.contrib.auth.models.DoesNotExist > > > The problem is, of course, that I can't assign an attribute sans the > > ability to specify which attribute I'm after... Does anyone have any > > suggestions? > > I'd suggest you post more of your code :-) > > The error trace by itself doesn't really help - it just tells us that > you're getting a DoesNotExist exception. The getattr()/setattr() > approach of dynamically modifying attributes works (I use it all the > time), so if it's not working for you, there is something else going > on. However, we can't really tell what that is without some sample > code. > > Yours, > Russ Magee %-) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---