Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#3074 closed defect (worksforme)

[bug] OneToOneField referencing a different app does not always register a Reverse Lookup.

Reported by: nowell strite Owned by: adrian
Component: Database layer (models, ORM) Version: 0.95
Severity: normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

OneToOneField does not register a Reverse Lookup when the relation references a different application. See the example below.

Create project, application, and models

/project/appone/models.py

from django.db import models

class Foo(models.Model):
    w = models.CharField(maxlength=20)

class Bar(models.Model):
    x = models.CharField(maxlength=10)
    y = models.ManyToManyField(Foo)

/project/apptwo/models.py

from django.db import models
from project.appone.models import Bar

class Baz(models.Model):
    bar = models.OneToOneField(Bar)

Setup test data

  • Add appone and apptwo to the INSTALLED_APPLICATIONS
  • Run python manage.py syncdb
  • Run python manage.py shell
    >>> from appone.models import *
    >>> from apptwo.models import *
    >>> a = Foo()
    >>> a.w = '1'
    >>> a.save()
    
    >>> b = Bar()
    >>> b.x = '2'
    >>> b.save()
    >>> b.y = [a]
    
    >>> c = Baz()
    >>> c.bar = b
    >>> c.save()
    
  • Next exit the shell environment to simulate a fresh environment
  • run python manage.py shell

This doesn't work

>>> from appone.models import Bar
>>> d = Bar.objects.all()[0]
>>> d.baz
Traceback (most recent call last):
  File "<console>", line 1, in ?
AttributeError: 'Bar' object has no attribute 'baz'

This works

>>> from appone.models import Bar
>>> d = Bar.objects.get(pk=1)
>>> d.baz

Change History (3)

comment:1 Changed 9 years ago by ubernostrum

IIRC, both models have to be imported before the reverse relationship will exist; if no model with a relation to one currently available has been imported, Django has no way of knowing that such a relation exists.

comment:2 Changed 9 years ago by anonymous

  • Resolution set to worksforme
  • Status changed from new to closed

comment:3 Changed 9 years ago by anonymous

  • milestone Version 1.0 deleted

Milestone Version 1.0 deleted

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