django OneToOne reverse access

WindowsMaker picture WindowsMaker · Jun 18, 2012 · Viewed 32.9k times · Source

I have these simple classes

Class A(models.Model):
    ...

Class Meta(models.Model):
    a = models.OnetoOneField(A, primary_key=True)
    width = models.IntegerField(default=100)

but when I do

a = A()
meta = Meta()
a.save()
meta.a = a
meta.save()
print a.meta.width

i get

'A' object has no attribute 'meta'

Why is this? Am I using OneToOne wrong? if so how can i get the correct print statement?

Thanks

Answer

Yuji 'Tomita' Tomita picture Yuji 'Tomita' Tomita · Jun 18, 2012

Define a related_name to call the reverse accessor.

a = models.OneToOneField(A, related_name='foobar')
# ...
a.foobar