On Tue, Oct 7, 2008 at 9:59 PM, Alex G <[EMAIL PROTECTED]> wrote:
>
> 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?

Your example isn't completely symmetric - I'm willing to be that if you tried:

>>> mymodel.some_relation_or_fk

you will get the same traceback.
Traceback (most recent call last):
...
DoesNotExist

Look carefully at what the error says - it's telling you that the
object that you have tried to retrieve doesn't exist - that is, the
object that is currently referred to by 'some_relation_or_fk' doesn't
exist.

If you look in the underlying table, you will probably find that the
some_relation_or_fk_id column contains a value (say, 3), but the
related model doesn't have a instance with id=3. This can only happen
if you're using a database without row-referential integrity (SQLite
or MySQL with MyISAM).

Also, just because you're getting errors with getattr doesn't mean you
can't use setattr. In fact, in this case, the opposite is true - you
need to set the field to get rid of the data integrity problem.

You also need to be clear about which end of the relation we are
dealing with. The error you are raising suggests that
'some_relation_or_fk' is the 'One' end of a OneToMany relation (i.e.,
a foreign key) - yet your original code snippet talks about calling
add(). If this is the case, you're dealing with the wrong end of the
snake :-)

As I said previously - we're going to need code to diagnose the
problem. Specifically, the model that is causing problems. Talking in
the abstract about 'some_relation_or_fk' is only going to give us both
headaches :-)

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
-~----------~----~----~----~------~----~------~--~---

Reply via email to