2

If I use

setattr(p,'wrong_attr','value')

instead of

p=MyModel.objects.filter(WRONG_ATTRIBUTE=value)

I don't get the error related to the non existent attribute. Is there a way to get that error using setattr?

Thank you.

foebu
  • 1,365
  • 2
  • 18
  • 35
  • `setattr` does not raise exceptions. You can instead put `p.wrong_attr` in `try..except` and handle it appropriately – karthikr Apr 01 '14 at 15:23

1 Answers1

2

These two commands are not in any way related. The equivalent of your setattr call is this:

p.wrong_attr = 'value'

which does not raise an error either, as Django model instances are just Python objects, and Python objects allow you to set attributes arbitrarily.

If you're asking how you can find whether "wrong_attr" is a valid field name, you can look in some of the methods of p._meta, such as get_all_field_names().

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    If raising an exception is the sought outcome (as it seems from the question), `p._meta.get_field('wrong_attr')` would do the trick, raising a `FieldDoesNotExist` exception. – lanzz Apr 01 '14 at 15:48
  • The p._meta.get_field('wrong_attr') is what I was looking for! ;) Thank you! (where I click for giving a karma point?) – foebu Apr 01 '14 at 16:31