Skip to content

Instantly share code, notes, and snippets.

@groovecoder
Created August 14, 2013 18:55
Show Gist options
  • Save groovecoder/6234298 to your computer and use it in GitHub Desktop.
Save groovecoder/6234298 to your computer and use it in GitHub Desktop.
def _inherited(parent_attr, direct_attr):
"""Return a descriptor delegating to an attr of the original document.
If `self` is a translation, the descriptor delegates to the attribute
`parent_attr` from the original document. Otherwise, it delegates to the
attribute `direct_attr` from `self`.
Use this only on a reference to another object, like a ManyToMany or a
ForeignKey. Using it on a normal field won't work well, as it'll preclude
the use of that field in QuerySet field lookups. Also, ModelForms that are
passed instance=this_obj won't see the inherited value.
"""
getter = lambda self: (getattr(self.parent, parent_attr)
if self.parent and
self.parent.id != self.id
else getattr(self, direct_attr))
setter = lambda self, val: (setattr(self.parent, parent_attr,
val) if self.parent and
self.parent.id != self.id else
setattr(self, direct_attr, val))
return property(getter, setter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment