Django: How to access originating instance from a RelatedManager?
-
19-09-2019 - |
Question
I would like to access the Foo
instance foo
within my manager method baz
:
foo.bar_set.baz()
baz
would normally take an argument of Foo
type:
BarManager(models.Manager):
def baz(self, foo=None):
if foo is None:
# assume this call originates from
# a RelatedManager and set `foo`.
# Otherwise raise an exception
# do something cool with foo
This way both the first query above and the following one works identically:
Bar.objects.baz(foo)
Bar
would have a ForeignKey to Foo
:
class Bar(models.Model):
foo = models.ForeignKey(Foo)
objects = BarManager()
Solution
If I'm understanding what you want correctly, you need to do this:
BarManager(models.Manager):
use_for_related_fields = True
Edit: apparently I managed to miss the point completely. You can use something like this (maybe a bit too "magic" for my taste, but oh well):
class BarManager(models.Manager):
use_for_related_fields = True
def bar(self, foo=None):
if foo == None:
qs = Foo.objects.all()
for field_name, field_val in self.core_filters.items():
field_name = field_name.split('__')[1]
qs = qs.filter(**{ field_name: field_val })
foo = qs.get()
# do k00l stuff with foo
OTHER TIPS
In Django 2.1 at least, you can simply do:
foo.bar_set.instance
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow