Opened 13 years ago

Closed 13 years ago

#16962 closed Bug (duplicate)

DoesNotExist when checking for related_name on OneToOneField

Reported by: dan@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Reproducible test case:

class Example(models.Model):
    parent = models.OneToOneField('self', null=True, blank=True,
            related_name='child')

    def __unicode__(self):
        return "%s" % self.function

Console

>>> example = Example.objects.create()
>>> example2 = Example.objects.create(parent=example)
>>> example2.child # should return None, instead throws traceback
/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/db/models/fields/related.pyc in __get__(self, instance, instance_type)
    238             db = router.db_for_read(self.related.model, instance=instance)
--> 239             rel_obj = self.related.model._base_manager.using(db).get(**params)
    240             setattr(instance, self.cache_name, rel_obj)
    241             return rel_obj

/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs)
    347         if not num:
    348             raise self.model.DoesNotExist("%s matching query does not exist."
--> 349                     % self.model._meta.object_name)
    350         raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s"
    351                 % (self.model._meta.object_name, num, kwargs))

DoesNotExist: Example matching query does not exist.

I considered sending in a patch to throw lines 238-240 in a try/except block, but I'm not sure that's the best way to solve this issue. I will submit something if a suggestion is made (I'm not super familiar with the Django codebase, so I might need some hand-holding).

Change History (2)

comment:1 by dan@…, 13 years ago

Maybe an error should be thrown when a related_name is set on a OneToOneField...

comment:2 by Andreas Pelme, 13 years ago

Resolution: duplicate
Status: newclosed

I have been bitten by this seemingly strange behavior myself in the past, and there is an open ticket for this:

Ticket #3106 and #10227 refers to the same problem. See those tickets for discussions on why it has not been fixed yet.

I am closing this ticket as duplicate, please reopen it and explain why if I am missing something that has not been brought to attention in the other ticket!

Note: See TracTickets for help on using tickets.
Back to Top