Mutual foo.bar and bar.foo attributes in django Models with onetooneviews
I have two classes, Foo and Bar, in a Django app (on AppEngine if that matters). There's a one to one relationship between them.
class Foo(BaseModel):
bar = Bar.objects.get(foo=self.id)
class Bar(BaseModel):
foo = models.OneToOneField(Foo, blank=True, null=True, help_text="Foos for this bar")
I'd like each object of both classes to have it's related object of the other class as an instance variable.
What's the best way开发者_开发知识库 to allow that?
When trying the code above, I'm in an odd situation: since they each refer to each other, I'm trying to use these variables before they're defined (and of course it doesn't work).
I suspect there is A Proper Way to do this, and this isn't it!
You don't need to do anything. This is the default behaviour. Just define the relationship in Bar
, and Foo
will automatically get a bar
attribute.
精彩评论