54

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

WindowsMaker
  • 3,132
  • 7
  • 29
  • 46

1 Answers1

84

Define a related_name to call the reverse accessor.

a = models.OneToOneField(A, related_name='foobar')
# ...
a.foobar 
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 20
    You could use a.meta instead of a.foobar in the absence of a related_name. But definitely don't call a model 'Meta'. – northben Jul 09 '14 at 19:19
  • 9
    Also useful to mention, if you don't use `related_name`, use model name with all letters in lower case. For example, if you have ExtraModel instead of Meta, you should access it like this: `a.extramodel`. – andrey Jan 15 '19 at 19:03
  • ref.: https://docs.djangoproject.com/en/2.1/topics/db/examples/one_to_one/ – sebhaase Mar 26 '19 at 10:51