calling hasattr(model_instance, fieldname) raises DoesNotExist when False
|Reported by:||monkut||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Cc:||charettes||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Using python 3.3 and django 1.6.
I've got a model (created from an AbstractBaseClass) and creating an instance of the model from some JSON, via serializers.deserialize(), then checking if the resulting parsed JSON model has the fields I'm expecting.
(thinking about it now, this seems like the wrong thing to do, since it may be expected that the resulting Model instance has the field, but takes the default value? but anyway...)
When I check to see if the parsed instance.object has the given attribute, via hasattr(), it's raising DoesNotExist, instead of returning the expected False.
Again, maybe it's ok that it doesn't return False... but I don't think hasattr() should raise an exception.
from django.contrib.auth.models import User class BaseTask(models.Model): assigned_to = models.ForiegnKey(User) class Meta: abstract = True class Task(BaseTask): pass
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from myproject.myapp.models import Task >>> from django.contrib.auth.models import User >>> t = Task() >>> hasattr(t, "assigned_to") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python33\lib\site-packages\django\db\models\fields\related.py", line 314, in __get__ "%s has no %s." % (self.field.model.__name__, self.field.name)) django.contrib.auth.models.DoesNotExist: Task has no assigned_to. >>> u = User.objects.get(pk=1) >>> >>> t.assigned_to = u >>> hasattr(t, "assigned_to") True >>>
Change History (6)
comment:1 follow-up: ↓ 2 Changed 3 years ago by aaugustin
- Component changed from Uncategorized to Database layer (models, ORM)
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
- Type changed from Uncategorized to Cleanup/optimization
comment:5 Changed 3 years ago by charettes
- Cc charettes added
- Has patch set
- Triage Stage changed from Accepted to Ready for checkin
- Version changed from 1.6 to master