Cannot access related field of an unsaved object if the object is from an inherited model
See the code below:
from django.test import TestCase
from django.db import models
class Parent(models.Model):
pass
class Child(Parent):
pass
class Sibling(models.Model):
child = models.ForeignKey(Child)
class BaseLine(models.Model):
parent = models.ForeignKey(Parent)
class RelTest(TestCase):
def test_relation(self):
child = Child()
child.save()
assert child.sibling_set, 'This will pass'
parent = Parent()
parent.save()
assert parent.baseline_set, 'This will pass'
new_parent = Parent()
assert parent.baseline_set, 'This will pass'
new_child = Child()
assert new_child.sibling_set, 'This will cause an exception'
Traceback (most recent call last):
File "/home/zbyte/Projects/bugs/bug/tests.py", line 27, in test_relation
assert new_child.sibling_set, 'This will cause an exception'
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py", line 324, in __get__
self.related.model._default_manager.__class__)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py", line 399, in create_manager
getattr(instance, attname)}
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py", line 244, in __get__
raise self.field.rel.to.DoesNotExist
DoesNotExist
As you can see this is only an issue if the model is inherited from another model. It should either return a None() queryset or this exception should be consistently raised in the other instance.
Change History
(12)
milestone: |
→ 1.2
|
Triage Stage: |
Unreviewed → Accepted
|
Owner: |
changed from nobody to Natalia Bidart
|
Status: |
new → assigned
|
Owner: |
Natalia Bidart removed
|
Status: |
assigned → new
|
Severity: |
→ Normal
|
Type: |
→ Bug
|
Resolution: |
→ fixed
|
Status: |
new → closed
|
Even though the example is not correct (when creating the
new_parent
object, the old, savedparent
instance is used to query thebaseline_set
instead of the unsavednew_parent
), the problem still persists when doing: