Reputation: 73
please I have an issue with model relationships in my Django project. For instance I have a model Foo
which inherits from a model mixin FooBarMixin
which is an abstract class and Bar
which is a model but has a OnetoOne
relationship with Foo
. Basically this is the current implementation.
class Foo(FooBarMixin):
pass
class FooBarMixin(model.Model):
bar = model.OneToOneField(Bar, on_delete=CASCADE,
related_name="tracked_%(class)s")
class Meta:
abstract = True
class Bar(model.Model):
pass
Is it possible to store Bar
data on the child model Foo
without using a OnetoOne
relationship ? and if so how do I go about it? Thank you
Upvotes: 2
Views: 281
Reputation: 476740
Sorry I meant I want the fields in
Bar
to be visible on theFoo
table.
Based on your comment you thus want to fetch fields of the Bar
relation in Foo
instances.
We could do that by patching the __getattr__
function:
class Foo(FooBarMixin):
def __getattr__(self, name):
try:
return super(Foo, self).__getattr__(name)
except AttributeError:
return getattr(self.bar, name)
So in case the attribute can not be fecthed from the Foo
instance itself, we fallback on the corresponding self.bar
object, and aim to obtain the attribute at that place.
Setting the attribute would require to override the __setattr__
function in a similar way, although I would advice against that, since it will introduce all kinds of side-effects (saving the corresponding .bar
object, etc.).
Upvotes: 1